Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Count the number of distinct ways to reach target t by putting + or − in front of every number.

Problem: Count the number of distinct ways to reach target t by putting + or − in front of every number.
from functools import lru_cache
def ways(a, t):
    @lru_cache(None)
    def go(i, s):
        if i == len(a): return int(s == t)
        return go(i + 1, s + a[i]) + go(i + 1, s - a[i])
    return go(0, 0)
print(ways((1, 1, 1, 1, 1), 3), ways((1, 0), 1), ways((2, 3), 4))
What is printed?
  1. A. 5 1 0
  2. B. 5 2 0
  3. C. 10 2 0
  4. D. 5 2 1

Correct answer: B. 5 2 0

Memoised on (index, running sum). For five 1s, choose which single 1 is negative: 5 ways. A 0 can be +0 or −0, which counts as two different sign assignments, so (1, 0) → 2. ±2 ± 3 is never 4. States ≤ n × (2·sum + 1).

More Coding Interview Problems questions

Exams that ask this topic