Counting Binary-Digit Base-4 Integers Below N

Medium · Coding & Algorithms · Data Scientist · Online Assessment

Problem Statement

Define a positive integer as fancy if its standard base-4 representation (written without leading zeros) uses exclusively the digits 0 and 1—never 2 or 3.

def count_fancy_numbers(n: int) -> int:

Given a positive integer n, compute how many positive fancy integers are strictly smaller than n (that is, integers x satisfying 1 <= x < n).

Because n can be as large as 10^18, testing numbers one at a time from 1 up to n - 1 is far too slow; your implementation should run in O(log n) time.

Examples

Example 1

Input: n = 24
Output: 7

Walk-through: In base 4, 24 = 1 * 16 + 2 * 4 + 0 * 1, written "120". The positive fancy integers strictly below 24 are: - 1 ("1" in base 4) - 4 ("10" in base 4) - 5 ("11" in base 4) - 16 ("100" in base 4) - 17 ("101" in base 4) - 20 ("110" in base 4) - 21 ("111" in base 4)

All 7 of those values are strictly less than 24.

Example 2

Input: n = 20
Output: 5

Walk-through: In base 4, 20 = 1 * 16 + 1 * 4 + 0 * 1, written "110". Even though 20 itself only uses 0 and 1 in base 4, the bound is strict (x < 20), so 20 is excluded. The 5 qualifying integers are 1, 4, 5, 16, and 17.

Constraints

  • 1 <= n <= 10^18

Step-by-step walkthrough

  1. Restate the problem and constraints

    A positive integer is called fancy when its base-4 expansion (writing the number as a sum of powers of 4: 1, 4, 16, 64, ... with digits 0, 1, 2, 3 and no leading zeros) contains exclusively 0 and 1. Given n (1 <= n <= 10^18), we want to count how many positive fancy integers x satisfy 1 <= x < n.

    Watch two crucial boundary rules: - Positive only: 0 is not positive, so counting begins at 1. - Strict upper bound (x < n): When n itself is fancy—such as Example 2, n = 20, which is 1*16 + 1*4 + 0*1 = "110" in base 4—we must not count n itself (5 smaller fancy numbers, not 6).

    Because 4^30 ≈ 1.15 * 10^18 > 10^18, n has at most 30 base-4 digits. Scanning n one base-4 digit at a time finishes in at most 30 loop iterations.

  2. Why scanning `1..n-1` is too slow, and the binary bijection

    Testing every integer x from 1 to n - 1 takes O(n log n) work—up to 10^18 iterations, which will never finish in time. Even generating only fancy numbers one by one visits up to 2^30 - 1 ≈ 1.07 * 10^9 numbers, which is still far too slow.

    To count without listing, line up the first seven positive binary integers alongside the first seven fancy integers written in base 4:

    Rank (decimal)   Binary (base 2)   Same 0/1 string in base 4   Decimal value
    --------------   ---------------   -------------------------   -------------
          1                 1                      1                     1
          2                10                     10                     4
          3                11                     11                     5
          4               100                    100                    16
          5               101                    101                    17
          6               110                    110                    20
          7               111                    111                    21
    

    Every positive binary string of 0s and 1s, when interpreted in base 4 instead of base 2, yields a unique fancy number—and because comparing two 0/1 strings works identically in base 2 and base 4 (longer strings are larger; for equal lengths, the leftmost differing bit wins), this bijection preserves exact sorted order!

    Consequently, the fancy integer whose base-4 digits spell the binary number b is literally the b-th smallest positive fancy integer, meaning there are b positive fancy integers less than or equal to it.

  3. Clamp at the first digit `>= 2` ("saturation")

    Thanks to that binary ranking, counting fancy integers strictly below n reduces to finding the largest 0/1 digit string below n and reading those bits in base 2!

    Sweep n's base-4 digits from left (most significant) to right (least significant): - While digit is 0 or 1: Copy digit directly. Picking 0 where n has 1 would discard valid larger fancy numbers that start with 1 at this position. - At the first digit >= 2 (2 or 3): We cannot copy 2 or 3, so the largest legal digit here is 1. Because 1 < digit at this high place value, our constructed number is already strictly smaller than n regardless of what goes into the remaining slots on the right! To build the largest fancy number below n, we greedily set this slot and every remaining slot to the right to 1 (we call this saturation).

    Compare the two possible outcomes at the end of the sweep:

    Case A — Saturation occurs (Example 1: n = 24, which is 1*16 + 2*4 + 0*1 = "120" in base 4):
      n in base 4:      1    2    0
                             ^-- first digit >= 2: clamp here and saturate rest with 1s!
      Chosen 0/1 bits:  1    1    1   ->  "111" in base 4 = 21 (< 24)
      Read in base 2:   111_2 = 7     ->  7 fancy numbers strictly below 24
    
    Case B — Never saturates (Example 2: n = 20, which is "110" in base 4):
      n in base 4:      1    1    0   (all digits already 0 or 1, so n itself is fancy!)
      Chosen 0/1 bits:  1    1    0   ->  "110" in base 4 = 20 (== n)
      Read in base 2:   110_2 = 6     ->  6 fancy numbers <= 20; subtract 1 -> 5 (< 20)
    
  4. Convert `n` to most-significant-first base-4 digits

    Repeatedly taking n % 4 peels off the rightmost (least significant) base-4 digit and n //= 4 shifts the remaining digits right. Reversing the collected list places the most significant digit at index 0:

    def base4_digits(n: int) -> List[int]:
        """Return the base-4 digits of positive integer n, most significant digit first."""
        # digits: reversed list collected least-significant-first, e.g. n = 24 -> [0, 2, 1] -> [1, 2, 0].
        digits: List[int] = []
        while n > 0:
            digits.append(n % 4)
            n //= 4
        digits.reverse()
        return digits
    
  5. Accumulate the binary rank in one pass

    We handle n <= 1 up front (0 positive integers lie strictly below 1). Next we sweep left to right across base4_digits(n), updating binary_rank = binary_rank * 2 + chosen_bit—the standard left-to-right binary shift-and-add rule. Finally, if saturated remains False after the loop, n itself was fancy and included in binary_rank, so we subtract 1:

    def count_fancy_numbers(n: int) -> int:
        """Count positive integers strictly less than n whose base-4 digits are all 0 or 1."""
        # Phase 1: Every positive fancy number is at least 1, so none are strictly less than 1.
        if n <= 1:
            return 0
    
        # Phase 2: Scan n's base-4 digits left-to-right to build the largest fancy number <= n,
        # interpreting its 0/1 digits as a base-2 integer (its 1-based rank among fancy numbers).
        # saturated: flips True at the first base-4 digit >= 2, unlocking all-1s to the right.
        binary_rank = 0
        saturated = False
    
        for digit in base4_digits(n):
            if digit >= 2:
                # Clamping a digit 2 or 3 down to 1 already stays strictly below n at this
                # place value, so every later position can greedily take the max allowed bit 1.
                saturated = True
    
            chosen_bit = 1 if saturated else digit
            binary_rank = binary_rank * 2 + chosen_bit
    
        # Phase 3: Enforce strict inequality (< n).
        # If saturated never became True, every base-4 digit of n was 0 or 1, meaning n itself
        # is fancy and was included in binary_rank; subtract 1 to exclude n.
        if not saturated:
            binary_rank -= 1
    
        return binary_rank
    
  6. Trace Example 1, Example 2, and `n = 100`

    Let's verify all three traces step by step:

    Example 1: n = 24 -> base4_digits(24) = [1, 2, 0]
      digit = 1 -> saturated = False -> chosen_bit = 1 -> binary_rank = 0*2 + 1 = 1
      digit = 2 -> saturated = True  -> chosen_bit = 1 -> binary_rank = 1*2 + 1 = 3
      digit = 0 -> saturated = True  -> chosen_bit = 1 -> binary_rank = 3*2 + 1 = 7
      End: saturated is True -> return 7   (note how trailing '0' became '1', counting 21 < 24!)
    
    Example 2: n = 20 -> base4_digits(20) = [1, 1, 0]
      digit = 1 -> saturated = False -> chosen_bit = 1 -> binary_rank = 1
      digit = 1 -> saturated = False -> chosen_bit = 1 -> binary_rank = 3
      digit = 0 -> saturated = False -> chosen_bit = 0 -> binary_rank = 6
      End: saturated is False -> 6 - 1 -> return 5   (excludes 20 itself)
    
    Larger trace: n = 100 -> base4_digits(100) = [1, 2, 1, 0]
      digit = 1 -> saturated = False -> chosen_bit = 1 -> binary_rank = 1
      digit = 2 -> saturated = True  -> chosen_bit = 1 -> binary_rank = 3
      digit = 1 -> saturated = True  -> chosen_bit = 1 -> binary_rank = 7
      digit = 0 -> saturated = True  -> chosen_bit = 1 -> binary_rank = 15
      End: saturated is True -> return 15  ("1111"_4 = 85 < 100)
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def base4_digits(n: int) -> List[int]:
        """Return the base-4 digits of positive integer n, most significant digit first."""
        # digits: reversed list collected least-significant-first, e.g. n = 24 -> [0, 2, 1] -> [1, 2, 0].
        digits: List[int] = []
        while n > 0:
            digits.append(n % 4)
            n //= 4
        digits.reverse()
        return digits
    
    
    def count_fancy_numbers(n: int) -> int:
        """Count positive integers strictly less than n whose base-4 digits are all 0 or 1."""
        # Phase 1: Every positive fancy number is at least 1, so none are strictly less than 1.
        if n <= 1:
            return 0
    
        # Phase 2: Scan n's base-4 digits left-to-right to build the largest fancy number <= n,
        # interpreting its 0/1 digits as a base-2 integer (its 1-based rank among fancy numbers).
        # saturated: flips True at the first base-4 digit >= 2, unlocking all-1s to the right.
        binary_rank = 0
        saturated = False
    
        for digit in base4_digits(n):
            if digit >= 2:
                # Clamping a digit 2 or 3 down to 1 already stays strictly below n at this
                # place value, so every later position can greedily take the max allowed bit 1.
                saturated = True
    
            chosen_bit = 1 if saturated else digit
            binary_rank = binary_rank * 2 + chosen_bit
    
        # Phase 3: Enforce strict inequality (< n).
        # If saturated never became True, every base-4 digit of n was 0 or 1, meaning n itself
        # is fancy and was included in binary_rank; subtract 1 to exclude n.
        if not saturated:
            binary_rank -= 1
    
        return binary_rank
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine an odometer built in base 4—a positional number system where each wheel shows 0, 1, 2, 3 and represents powers of 4 (1, 4, 16, 64, ...)—except 2 and 3 are taped over so only 0 and 1 are legal. Every allowed ("fancy") reading looks just like a binary number (1, 10, 11, 100, 101, ...), and reading that 0/1 string in base 2 tells you its exact 1-based position in the sorted list of fancy numbers (1 -> #1, 10_4 = 4 -> #2, 11_4 = 5 -> #3, 100_4 = 16 -> #4). To count fancy numbers strictly below n, we find the largest 0/1 base-4 reading below n—copying n's 0s and 1s from left to right until we hit the first 2 or 3, clamping that wheel and every wheel to its right to 1—and read those bits in binary!

Testing every integer from 1 to n - 1 one by one takes up to 10^18 checks, which would run for years on a modern CPU. Even generating only the 0/1 strings below 10^18 visits roughly 2^30 ≈ 1.07 billion fancy numbers, whereas inspecting n's base-4 wheels directly takes at most 30 tiny operations.

Let's trace our two examples to see both endings: - n = 24 ("120" in base 4): Copy the leading 1 (binary_rank = 1), then hit 2 >= 2, which flips saturated = True and clamps both the 2 and the trailing 0 to 1 (binary_rank goes 1 -> 3 -> 7). Because we saturated, "111"_4 = 21 is already strictly below 24, returning 7 ({1, 4, 5, 16, 17, 20, 21}). - n = 20 ("110" in base 4): Copy 1, 1, 0 (binary_rank goes 1 -> 3 -> 6) with saturated staying False. Because n = 20 itself is fancy and was included in 6, subtracting 1 returns 5 ({1, 4, 5, 16, 17}).

Complexity

  • Time: O(log_4 n) (equivalently O(log n)). Extracting base4_digits(n) divides n by 4 once per base-4 digit (at most 30 times for n <= 10^18), reverses that short list, and scans it once with O(1) arithmetic per digit.
  • Space: O(log_4 n) to hold the digits list of at most 30 integers (replaceable with O(1) space by inspecting pairs of bits in n from (n.bit_length() - 1) // 2 down to 0).

Edge cases

  • n = 1 (minimum valid input): No positive integer is strictly less than 1; our early if n <= 1: return 0 returns 0 immediately (and safely guards n <= 0 from ever returning -1).
  • n itself is fancy (1, 4, 5, 16, 17, 20, 21, ...): saturated stays False, and binary_rank -= 1 excludes n to satisfy strict < n.
  • Exact powers of four (n = 4^k, i.e., "1" followed by k zeros): binary_rank builds 10...0_2 = 2^k with saturated = False, then subtracts 1 to return 2^k - 1 (all non-empty 0/1 strings of length <= k).
  • Leading digit 2 or 3 (including n = 10^18, which starts with 3 across 30 base-4 digits): saturated becomes True on the very first digit, filling all L bits with 1 and returning 2^L - 1 (2^30 - 1 = 1,073,741,823 for 10^18).
  • 0 after a 2 or 3 (such as n = 24 = "120"_4 in Example 1): Once saturated flips True at '2', the trailing '0' still becomes '1' (7, not 6), because "111"_4 = 21 < 24.

Common mistakes

  • Forgetting to subtract 1 when n is fancy. Returning 6 instead of 5 on n = 20 counts <= n instead of < n.
  • Copying 0s after seeing a 2 or 3. If you only clamp digits >= 2 to 1 without remembering saturated = True, "120"_4 turns into "110"_2 = 6 instead of "111"_2 = 7, missing "111"_4 = 21 < 24.
  • Replacing the first 2 or 3 with 0 instead of 1 or truncating there. Putting 1 under a 2 or 3 is already strictly smaller than n, and stopping early loses all remaining place values.
  • Using floating-point math.log(n, 4) to count digits. Floating-point rounding near large powers like 4^29 can miscount by 1 (for example math.log(4**29 - 1, 4) rounds to 29.0!), whereas integer % 4 and // 4 are exact for all 64-bit integers.

Alternative approaches

  • Bit-pair inspection in O(1) extra space: Because 4 = 2^2, each base-4 digit of n is just a 2-bit pair (n >> (2 * i)) & 3 read from the highest pair down to i = 0, running the exact same saturated / binary_rank loop without allocating a digits list.
  • Digit dynamic programming (digit DP): Digit DP counts valid integers below n digit by digit while tracking a boolean tight flag indicating whether the prefix built so far still matches n's prefix; for digits {0, 1} in base 4, our greedy saturation rule is the closed-form simplification of that DP.

Follow-up questions

  • How would you adapt the algorithm to count positive integers below n whose base-b representation uses only digits from a given subset D? With an arbitrary subset D of size k = |D|, naive saturation can get stuck when n's forbidden digit has no smaller allowed digit (for instance, seeing digit 1 when D = {2, 3}—or seeing 1 at the leading position when D = {0, 2}, where leading 0 is illegal!). A clean digit DP sweep handles every subset uniformly in O(log_b n): first add all valid positive integers with strictly fewer digits than n (nonzero_choices * k^(length - 1) for each shorter length, since only 0 is barred from index 0), then walk n's base-b digits left-to-right, adding smaller_valid_choices * k^(remaining_slots) at each index i and breaking out of the loop the moment n's digit at i is not in D (which also automatically excludes n itself if the loop finishes!).

```python def count_allowed_below(n: int, base: int, allowed: Set[int]) -> int: if n <= 1: return 0 allowed_sorted = sorted(allowed) k = len(allowed_sorted) digits: List[int] = [] temp = n while temp > 0: digits.append(temp % base) temp //= base digits.reverse()

  total = 0
  nonzero = k - (1 if 0 in allowed else 0)
  for length in range(1, len(digits)):
      total += nonzero * (k ** (length - 1))

  for i, d in enumerate(digits):
      smaller = sum(1 for a in allowed_sorted if a < d and not (i == 0 and a == 0))
      total += smaller * (k ** (len(digits) - 1 - i))
      if d not in allowed:
          break
  return total

```

  • Instead of counting values below n, how would you compute the k-th smallest positive fancy integer? Invert the binary bijection! Write positive integer k in binary (bin(k)[2:]) and evaluate that exact string of 0s and 1s as a base-4 integer (int(bin(k)[2:], 4), or loop ans = ans * 4 + bit), running in O(log k) time—for example, k = 5 is "101"_2, which read in base 4 gives 1*16 + 0*4 + 1 = 17, the 5th fancy number (1, 4, 5, 16, 17).
  • What changes if n is passed as a decimal string of up to 10^5 digits? Repeatedly dividing a 10^5-digit number by 4 (1.66 * 10^5 output digits times O(L) per division) costs O(L^2) time (~10^10 operations, several seconds). Instead, parse the decimal string into binary in O(L log^2 L) using divide-and-conquer radix conversion (splitting the string in half recursively and combining via high * 10^m + low with fast big-integer multiplication; in Python, lifting sys.set_int_max_str_digits(0) and calling bin(int(s)) takes ~16 ms), then group adjacent binary bits in pairs from the right—because 4 = 2^2, each 2-bit pair is a base-4 digit in O(L) linear time! Finally, collect the resulting ~1.66 * 10^5 chosen_bits in a list (subtracting 1 on the bit array via a trailing-zero borrow if not saturated) and either fold modulo 10^9 + 7 in O(L) or convert back to decimal via divide-and-conquer rather than doing quadratic big-int rank * 2 + bit in a loop.

Follow-up questions

Similar questions

More Hudson River Trading interview questions

All 55 Hudson River Trading questions →