Data Structures & AlgorithmsVery hardProduct company OA

Digit DP (position, running sum, tight flag) counts integers in [0, N] whose digits sum to 10, cross-checked by brute force. What is printed?

Digit DP (position, running sum, tight flag) counts integers in [0, N] whose digits sum to 10, cross-checked by brute force. What is printed?
from functools import lru_cache
def count(N, target):
    D = list(map(int, str(N)))
    @lru_cache(None)
    def go(i, s, tight):
        if s > target: return 0
        if i == len(D): return int(s == target)
        hi = D[i] if tight else 9
        return sum(go(i + 1, s + d, tight and d == hi) for d in range(hi + 1))
    return go(0, 0, True)
print(count(1000, 10), count(2024, 10), sum(1 for x in range(1, 2025) if sum(map(int, str(x))) == 10))
  1. A. 63 119 119
  2. B. 63 120 120
  3. C. 66 120 120
  4. D. 63 108 120

Correct answer: B. 63 120 120

'tight' means the prefix so far equals N's prefix, so the next digit is capped by N's digit; otherwise 0–9 are free. Up to 1000 only 3-digit strings matter (1000 itself has digit sum 1): solutions of a + b + c = 10 with digits ≤ 9 are C(12, 2) − 3 = 63. Up to 2024 the DP gives 120, matching the brute-force count. The DP has O(digits · sum · 2) states, so it works for N up to 10¹⁸.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic