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

Problem: Count downward paths (starting anywhere, ending anywhere below) that sum to k, using prefix sums on the root-to-node path. Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).

Problem: Count downward paths (starting anywhere, ending anywhere below) that sum to k, using prefix sums on the root-to-node path. Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).
class T:
    def __init__(self, v, l=None, r=None):
        self.v, self.l, self.r = v, l, r
def build(xs, i=0):
    if i >= len(xs) or xs[i] is None: return None
    return T(xs[i], build(xs, 2*i+1), build(xs, 2*i+2))
from collections import defaultdict
def path_sum(root, k):
    seen = defaultdict(int); seen[0] = 1
    def dfs(t, cur):
        if not t: return 0
        cur += t.v
        res = seen[cur - k]
        seen[cur] += 1
        res += dfs(t.l, cur) + dfs(t.r, cur)
        seen[cur] -= 1
        return res
    return dfs(root, 0)
print(path_sum(build([10, 5, -3, 3, 2, None, 11, 3, -2, None, 1]), 8))
What is printed?
  1. A. 2
  2. B. 4
  3. C. 3
  4. D. 5

Correct answer: C. 3

Same idea as subarray-sum-k: the count of earlier prefix sums equal to cur − k gives paths ending here. Paths: 5 → 3, 5 → 2 → 1, −3 → 11. Decrementing seen[cur] when backtracking stops prefix sums leaking into sibling subtrees. O(n) versus O(n²) for starting a DFS from every node.

More Coding Interview Problems questions

Exams that ask this topic