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?
  1. A. 63 21
  2. B. 63 28
  3. C. 36 27
  4. 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

Exams that ask this topic