Data Structures & AlgorithmsVery hardGoogle · Flipkart interview
Problem: Count integers in [1, N] whose digits sum to S, with a digit DP over (position, sum so far, tight).
Problem: Count integers in [1, N] whose digits sum to S, with a digit DP over (position, sum so far, tight).
from functools import lru_cache
def count(N, S):
d = list(map(int, str(N)))
@lru_cache(None)
def go(i, s, tight):
if s > S: return 0
if i == len(d): return 1 if s == S else 0
hi = d[i] if tight else 9
return sum(go(i + 1, s + x, tight and x == hi) for x in range(hi + 1))
return go(0, 0, True)
print(count(1000, 10), count(250, 7))What is printed?- A. 63 21
- B. 63 28
- C. 36 27
- D. 54 20
Correct answer: A. 63 21
The tight flag limits the current digit to N's digit while the prefix equals N's prefix. Numbers up to 1000 with digit sum 10 number 63, and numbers in 1..250 with digit sum 7 number 21; both agree with a direct loop.
More Coding Interview Problems questions
- Problem: Assign 4 workers to 4 jobs (one each) to minimise total cost, with a DP over the bitmask of used jobs. python cost = [[9, 2, 7…
- Problem: Maximum independent set (largest set of pairwise non-adjacent nodes) in a TREE with a two-state DP. python from collections…
- Edge case: greedy coin change versus DP when the coin system is not canonical. python def greedy(coins, x): cnt = 0 for c in sorted(coins…
- Problem: Count the ways to climb n stairs taking 1, 3 or 5 steps at a time (order matters). python def ways(n): dp = [1] + [0] n for i in…
- Problem: Fractional knapsack — take items (or fractions) by value/weight ratio to maximise value within capacity. python def frac(items…
- Problem: One pass of Lomuto partition (pivot = last element) as used in quicksort. python def lomuto(a): p = a[-1]; i = -1 for j in…