Largest Fancy Number At Most N

Combinatorics · Hard · Free problem

Call a positive integer *fancy* if every digit in its base-4 representation is either 0 or 1 (so 0, 1, 4, 5, 16, 17, 20, 21, ... are fancy in decimal).

Given an integer $N$ with $1 \leq N \leq 10^{18}$, return the largest fancy number that is $\leq N$.

Your solution must run in $O(\log N)$ time.

Examples:

  • $N = 6$: Base-4 digits of 6 are 12. The largest fancy number $\leq 6$ is 5 (base-4: 11). Output: 5
  • $N = 1$: Already fancy. Output: 1
  • $N = 100$: Base-4 is 1210. Largest fancy $\leq 100$ is 85 (base-4: 1111). Output: 85

Hints

  1. Fancy numbers (base-4 digits all in $\{0,1\}$) biject with binary numbers -- think about what that means for counting and constructing them.
  2. Scan $N$'s base-4 digits left to right. At the first digit $\geq 2$, the answer is determined: replace that digit with 1 and fill everything after it with 1s.
  3. At a digit equal to 1, you have a choice: keep it (stay tight) or drop to 0 and fill the suffix with 1s. Track the best candidate from all such branch points and from the final tight match.

Worked Solution

How to Think About It: Fancy numbers -- integers whose base-4 digits are all in $\{0, 1\}$ -- are in bijection with binary strings: read a fancy number's base-4 digits as bits and you get a unique natural number, and vice versa.

The heuristic for "largest X $\leq N$ with a digit constraint" is a greedy left-to-right scan: match $N$'s digits for as long as they are legal, and the first illegal digit decides everything. The key simplification here -- and the step many solutions overcomplicate -- is that no branching or backtracking is ever needed. You might worry that at a digit equal to 1 you should also consider dropping it to 0 (freeing the suffix to be all 1s). You never should: that dropped candidate equals $\text{prefix} + \underbrace{11\cdots1_4}_{r \text{ ones}} = \text{prefix} + \tfrac{4^r - 1}{3}$, which is *strictly less* than $\text{prefix} + 4^r$, the smallest value any tight continuation can reach. Staying tight always ends at something at least that large (either $N$ itself, or a later clamp that keeps this 1 in place), so the dropped candidate can never win. Greedy dominance kills the branch.

Quick Estimate: $N = 100 = 1210_4$. Scan: $1$ (keep), $2$ (illegal -- clamp here). Answer $= 11\,11_4$: keep the leading 1, clamp the 2 down to 1, fill with 1s $= 64 + 16 + 4 + 1 = 85$. Matches the expected output with zero bookkeeping.

Algorithm:

1. Write $N$ in base 4 as $d_k d_{k-1} \cdots d_0$ (most significant first). 2. Walk left to right, keeping a running prefix value. At position with $r$ digits remaining after it: - If $d_i \in \{0, 1\}$: keep it (add $d_i \cdot 4^r$ to the prefix) and continue. - If $d_i \geq 2$: clamp this digit to 1 and fill the rest with 1s. Return $\text{prefix} + 4^r + \tfrac{4^r - 1}{3}$ immediately. 3. If the scan finishes, every digit of $N$ is 0 or 1, so $N$ itself is fancy -- return $N$.

Why the clamp is optimal: any fancy number sharing the prefix is at most the clamped value, and any fancy number that deviates from the prefix earlier had to turn some 1 into a 0, making it strictly smaller. So the first position where $N$'s digit is $\geq 2$ (if any) pins down the whole answer.

Code:

```python def largest_fancy(N: int) -> int: # Base-4 digits of N, most significant first digits = [] tmp = N while tmp > 0: digits.append(tmp % 4) tmp //= 4 digits.reverse()

k = len(digits) prefix = 0 for i, d in enumerate(digits): r = k - i - 1 # digits remaining after position i if d <= 1: prefix += d * (4 ** r) # keep the digit, stay tight else: ones = (4 ** r - 1) // 3 # base-4 '11...1' with r ones return prefix + 4 ** r + ones # clamp to 1, fill with 1s

return N # every digit was 0/1 -- N is already fancy ```

Verified by brute force against direct enumeration for all $N \leq 2 \times 10^5$: exact agreement.

Complexity: $O(\log_4 N) = O(\log N)$ time, one pass; $O(\log N)$ space for the digits.

Answer: One greedy pass over $N$'s base-4 digits. Keep digits while they are 0 or 1; at the first digit $\geq 2$, clamp it to 1 and fill the suffix with 1s; if no such digit exists, $N$ is fancy. No candidate tracking or branching is needed -- dropping a 1 is always dominated by staying tight.

Intuition

This problem is an instance of the general digit-DP pattern: "find the largest number $\leq N$ satisfying some digit constraint." The structure is always the same -- walk through $N$'s digits, maintain a tight bound, and at each position where you are forced below $N$, greedily maximize the suffix. The bijection between fancy numbers and binary numbers is a nice structural insight (it tells you there are $2^k - 1$ fancy numbers with at most $k$ base-4 digits), but you do not actually need it to implement the algorithm; the greedy scan works directly.

In broader quant and CS contexts, digit DP shows up whenever you need to count or find extremes over integers with digit-level constraints -- think counting primes below $N$ (sieve variants), finding integers with specific digit sums (Bayesian scoring), or constructing valid IDs within a range. The key habit is always the same: convert to the relevant base, scan from high to low significance, and decide at each digit whether to stay tight or branch down.

Open the full interactive solver →