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
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 digits0, 1, 2, 3and no leading zeros) contains exclusively0and1. Givenn(1 <= n <= 10^18), we want to count how many positive fancy integersxsatisfy1 <= x < n.Watch two crucial boundary rules: - Positive only:
0is not positive, so counting begins at1. - Strict upper bound (x < n): Whennitself is fancy—such as Example 2,n = 20, which is1*16 + 1*4 + 0*1 = "110"in base 4—we must not countnitself (5smaller fancy numbers, not6).Because
4^30 ≈ 1.15 * 10^18 > 10^18,nhas at most 30 base-4 digits. Scanningnone base-4 digit at a time finishes in at most 30 loop iterations.Why scanning `1..n-1` is too slow, and the binary bijection
Testing every integer
xfrom1ton - 1takesO(n log n)work—up to10^18iterations, which will never finish in time. Even generating only fancy numbers one by one visits up to2^30 - 1 ≈ 1.07 * 10^9numbers, 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 21Every positive binary string of
0s and1s, when interpreted in base 4 instead of base 2, yields a unique fancy number—and because comparing two0/1strings 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
bis literally theb-th smallest positive fancy integer, meaning there arebpositive fancy integers less than or equal to it.Clamp at the first digit `>= 2` ("saturation")
Thanks to that binary ranking, counting fancy integers strictly below
nreduces to finding the largest0/1digit string belownand reading those bits in base 2!Sweep
n's base-4 digits from left (most significant) to right (least significant): - Whiledigitis0or1: Copydigitdirectly. Picking0wherenhas1would discard valid larger fancy numbers that start with1at this position. - At the firstdigit >= 2(2or3): We cannot copy2or3, so the largest legal digit here is1. Because1 < digitat this high place value, our constructed number is already strictly smaller thannregardless of what goes into the remaining slots on the right! To build the largest fancy number belown, we greedily set this slot and every remaining slot to the right to1(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)Convert `n` to most-significant-first base-4 digits
Repeatedly taking
n % 4peels off the rightmost (least significant) base-4 digit andn //= 4shifts the remaining digits right. Reversing the collected list places the most significant digit at index0: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 digitsAccumulate the binary rank in one pass
We handle
n <= 1up front (0positive integers lie strictly below1). Next we sweep left to right acrossbase4_digits(n), updatingbinary_rank = binary_rank * 2 + chosen_bit—the standard left-to-right binary shift-and-add rule. Finally, ifsaturatedremainsFalseafter the loop,nitself was fancy and included inbinary_rank, so we subtract1: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_rankTrace 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)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)). Extractingbase4_digits(n)dividesnby4once per base-4 digit (at most30times forn <= 10^18), reverses that short list, and scans it once withO(1)arithmetic per digit. - Space: O(log_4 n) to hold the
digitslist of at most30integers (replaceable withO(1)space by inspecting pairs of bits innfrom(n.bit_length() - 1) // 2down to0).
Edge cases
n = 1(minimum valid input): No positive integer is strictly less than1; our earlyif n <= 1: return 0returns0immediately (and safely guardsn <= 0from ever returning-1).nitself is fancy (1, 4, 5, 16, 17, 20, 21, ...):saturatedstaysFalse, andbinary_rank -= 1excludesnto satisfy strict< n.- Exact powers of four (
n = 4^k, i.e.,"1"followed bykzeros):binary_rankbuilds10...0_2 = 2^kwithsaturated = False, then subtracts1to return2^k - 1(all non-empty0/1strings of length<= k). - Leading digit
2or3(includingn = 10^18, which starts with3across30base-4 digits):saturatedbecomesTrueon the very first digit, filling allLbits with1and returning2^L - 1(2^30 - 1 = 1,073,741,823for10^18). 0after a2or3(such asn = 24 = "120"_4in Example 1): OncesaturatedflipsTrueat'2', the trailing'0'still becomes'1'(7, not6), because"111"_4 = 21 < 24.
Common mistakes
- Forgetting to subtract
1whennis fancy. Returning6instead of5onn = 20counts<= ninstead of< n. - Copying
0s after seeing a2or3. If you only clamp digits>= 2to1without rememberingsaturated = True,"120"_4turns into"110"_2 = 6instead of"111"_2 = 7, missing"111"_4 = 21 < 24. - Replacing the first
2or3with0instead of1or truncating there. Putting1under a2or3is already strictly smaller thann, and stopping early loses all remaining place values. - Using floating-point
math.log(n, 4)to count digits. Floating-point rounding near large powers like4^29can miscount by1(for examplemath.log(4**29 - 1, 4)rounds to29.0!), whereas integer% 4and// 4are exact for all 64-bit integers.
Alternative approaches
- Bit-pair inspection in
O(1)extra space: Because4 = 2^2, each base-4 digit ofnis just a 2-bit pair(n >> (2 * i)) & 3read from the highest pair down toi = 0, running the exact samesaturated/binary_rankloop without allocating adigitslist. - Digit dynamic programming (digit DP): Digit DP counts valid integers below
ndigit by digit while tracking a booleantightflag indicating whether the prefix built so far still matchesn's prefix; for digits{0, 1}in base4, 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
nwhose base-brepresentation uses only digits from a given subsetD? With an arbitrary subsetDof sizek = |D|, naive saturation can get stuck whenn's forbidden digit has no smaller allowed digit (for instance, seeing digit1whenD = {2, 3}—or seeing1at the leading position whenD = {0, 2}, where leading0is illegal!). A clean digit DP sweep handles every subset uniformly inO(log_b n): first add all valid positive integers with strictly fewer digits thann(nonzero_choices * k^(length - 1)for each shorterlength, since only0is barred from index0), then walkn's base-bdigits left-to-right, addingsmaller_valid_choices * k^(remaining_slots)at each indexiand breaking out of the loop the momentn's digit atiis not inD(which also automatically excludesnitself 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 thek-th smallest positive fancy integer? Invert the binary bijection! Write positive integerkin binary (bin(k)[2:]) and evaluate that exact string of0s and1s as a base-4 integer (int(bin(k)[2:], 4), or loopans = ans * 4 + bit), running inO(log k)time—for example,k = 5is"101"_2, which read in base 4 gives1*16 + 0*4 + 1 = 17, the 5th fancy number (1, 4, 5, 16, 17). - What changes if
nis passed as a decimal string of up to10^5digits? Repeatedly dividing a10^5-digit number by4(1.66 * 10^5output digits timesO(L)per division) costsO(L^2)time (~10^10operations, several seconds). Instead, parse the decimal string into binary inO(L log^2 L)using divide-and-conquer radix conversion (splitting the string in half recursively and combining viahigh * 10^m + lowwith fast big-integer multiplication; in Python, liftingsys.set_int_max_str_digits(0)and callingbin(int(s))takes~16 ms), then group adjacent binary bits in pairs from the right—because4 = 2^2, each 2-bit pair is a base-4 digit inO(L)linear time! Finally, collect the resulting~1.66 * 10^5chosen_bits in a list (subtracting1on the bit array via a trailing-zero borrow ifnot saturated) and either fold modulo10^9 + 7inO(L)or convert back to decimal via divide-and-conquer rather than doing quadratic big-intrank * 2 + bitin a loop.
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`?
- Instead of counting values below `n`, how would you compute the `k`-th smallest positive fancy integer?
- What changes if `n` is passed as a decimal string of up to `10^5` digits?
Similar questions
- Structuring Implementation-Heavy Data Structures
- Simulating a Marble on a Timed Tilting Grid
- Task Completion Timestamps on a Bounded Single-Worker Queue
- Verify Root-to-Leaf Path Sum
- Counting Index Pairs Equivalent Under Repeated Digit Reversals
- Permutation Inversion Counter
More Hudson River Trading interview questions
- Simulating a Marble on a Timed Tilting Grid Easy
- Track Sentry Simulation and Manual Integer Formatting Medium
- Structuring Implementation-Heavy Data Structures Medium Pro
- End-to-End Cardiac Risk Classification Workflow Hard Pro
- Verify Root-to-Leaf Path Sum Easy Pro
- Sample Mean vs. Median Under Zero-Inflated Normals Medium Pro
- Lifecycle-Tracked Lazy File Streaming in Python Medium Pro
- Counting Arrivals Past a Switching Lookout Easy Pro
- Aligned Slab-Backed Pool Allocator Design Medium Pro
- Systematic Custom Test Suite Design Under Coding Assessment Time Limits Medium Pro