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?- A. 90 1561
- B. 81 1561
- C. 91 1561
- 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
- Problem: Count all valid topological orderings of a small DAG (n ≤ 20) with a DP over subsets: from a set of already placed nodes, place…
- Problem: A traffic monitor reports, for every window of k consecutive minutes, the busiest minute's count, and the dashboard shows the SUM…
- Problem: Find the maximum sum of a non-empty subarray of a CIRCULAR array (a subarray may wrap from the end to the start). python def…
- Problem: Install c routers at some of the given highway mile-markers so that the smallest distance between any two routers is as LARGE as…
- A divide-and-conquer routine satisfies T(n) = 4T(n/2) + n² log n. What is its running time?
- Edge case: A helper collects items into a list using a default argument. python def collect(x, out=[]): out.append(x) return out a =…