Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Count integers in [1, N] whose decimal digits have no two adjacent equal digits, using digit DP with states (position, previous digit, tight, started).

Problem: Count integers in [1, N] whose decimal digits have no two adjacent equal digits, using digit DP with states (position, previous digit, tight, started).
from functools import lru_cache
def no_adjacent_equal(N):
    s = str(N)
    @lru_cache(None)
    def go(i, prev, tight, started):
        if i == len(s): return 1 if started else 0
        lim = int(s[i]) if tight else 9; total = 0
        for d in range(lim + 1):
            if started and d == prev: continue
            ns = started or d != 0
            total += go(i + 1, d if ns else -1, tight and d == lim, ns)
        return total
    return go(0, -1, True, False)
print(no_adjacent_equal(100), no_adjacent_equal(2024))
What is printed?
  1. A. 90 1561
  2. B. 81 1561
  3. C. 91 1561
  4. D. 90 1640

Correct answer: A. 90 1561

'tight' keeps the prefix ≤ N, 'started' ignores leading zeros (so 0 before the first real digit does not count as a repeat). 1..100: all 9 one-digit numbers, 81 of the 90 two-digit numbers (not 11, 22, …, 99), and 100 fails (00) → 90. For 2024 the DP gives 1561, matching a brute-force scan. Digit DP is O(digits · 10 · 10 · 4), so it handles N = 10¹⁸ where scanning cannot.

More Coding Interview Problems questions

Exams that ask this topic