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

Problem: A thief robs houses arranged as a binary tree; robbing two directly linked houses triggers an alarm. Each node returns (best if robbed, best if skipped). Trees are built from a level-order list by build(xs) (None = missing child), shown in the code.

Problem: A thief robs houses arranged as a binary tree; robbing two directly linked houses triggers an alarm. Each node returns (best if robbed, best if skipped). Trees are built from a level-order list by build(xs) (None = missing child), shown in the code.
from collections import deque
class T:
    def __init__(s, v): s.v, s.l, s.r = v, None, None
def build(xs):  # level order, None = missing child
    root = T(xs[0]); q = deque([root]); i = 1
    while i < len(xs):
        node = q.popleft()
        for side in ("l", "r"):
            if i < len(xs) and xs[i] is not None:
                setattr(node, side, T(xs[i])); q.append(getattr(node, side))
            i += 1
    return root
def rob(t):
    def go(t):
        if not t: return (0, 0)
        l, r = go(t.l), go(t.r)
        return (t.v + l[1] + r[1], max(l) + max(r))
    return max(go(t))
print(rob(build([4, 1, 5, 6, 2, None, 3])), rob(build([2, 9, 3, 1, None, None, 8])))
What is printed?
  1. A. 13 17
  2. B. 15 11
  3. C. 15 17
  4. D. 16 17

Correct answer: C. 15 17

Robbing a node forces skipping its children; skipping it lets each child choose its own best. First tree 4 → (1, 5), 1 → (6, 2), 5 → (–, 3): rob 4 + 6 + 2 + 3 = 15 (skipping 1 and 5). Second 2 → (9, 3), 9 → (1, –), 3 → (–, 8): rob 9 + 8 = 17. Taking alternate levels fails: in the second tree it gives max(2 + 1 + 8, 9 + 3) = 12. O(n).

More Coding Interview Problems questions

Exams that ask this topic