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?- A. 2
- B. 4
- C. 3
- 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
- Problem: Serialize a tree in preorder with '#' for missing children, then count the nodes from the string alone. python class T: def…
- Problem: Rebuild a tree from its preorder and inorder sequences (distinct values) and print its postorder. python def post(pre, ino): if…
- Problem: Check whether a tree is height-balanced (every node's subtree heights differ by at most 1). Trees are built by build(xs): a…
- Problem: Return the zigzag level order (left→right, then right→left, alternating). Trees are built by build(xs): a level-order list where…
- Problem: Convert a sorted array into a height-balanced BST and print its preorder. python def pre(a, lo, hi, out): if lo > hi: return out…
- Problem: A tree has n = 10⁵ nodes and arrives as a parent array. You must answer 10⁵ queries 'is u an ancestor of v?'. Which preprocessing…