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))- A. 63 119 119
- B. 63 120 120
- C. 66 120 120
- 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¹⁸.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- All suffixes of 'banana' are inserted into a character trie (a suffix trie). What is printed (trie nodes including the root, distinct…
- BFS 2-colouring of each component of an undirected graph. What is printed (components, bipartite components)? python from collections…
- Binary lifting for lowest common ancestors (up[k][v] is the 2ᵏ-th ancestor; the root is its own parent). What is printed? python LOG = 4…
- Brute force over all 4-edge subsets of a 5-vertex weighted graph with repeated weights. What is printed (MST weight, number of distinct…
- Floyd–Warshall with the correct loop order (k outermost) and with k innermost. What is printed (d[0][1], d[2][0], d[0][3] for each)?…
- Tarjan's SCC algorithm, then the condensation DAG. What is printed (SCCs, source components, sink components, minimum edges to add to make…