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?- A. 5 1 0
- B. 5 2 0
- C. 10 2 0
- 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
- Problem: Generate all subsets of a set of feature flags (backtracking) and count those whose sum equals a target. python def count(a, t…
- Problem: Generate all permutations of a list that may contain duplicates, without repeats. How many are produced? python def perms(a)…
- Problem: Generate all valid strings of n pairs of brackets in lexicographic order of the recursion ('(' tried first). python def gen(n)…
- Problem: Count the ways to place n queens on an n × n board so none attack each other. python def queens(n): cols, d1, d2 = set(), set()…
- Problem: Find whether a word exists in a letter grid by moving to adjacent (up/down/left/right) cells without reusing a cell. python def…
- Problem: List all combinations of k numbers from 1..n that sum to s (each number used at most once). python def combo(k, s, n=9): out = []…