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?- A. 13 17
- B. 15 11
- C. 15 17
- 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
- Problem: Place the minimum number of cameras on tree nodes so every node is monitored (a camera covers itself, its parent and its…
- Problem: A tree of n nodes holds n coins in total, unevenly. A move transfers one coin between adjacent nodes. Minimum moves so every node…
- Problem: Return all node values at exactly distance k from a target node (distance counts edges, moving up or down). Record parent…
- Problem: Rocks are smashed repeatedly: take the two heaviest; if equal both vanish, otherwise the difference remains. Report the last…
- Problem: Room 0 is open; each room holds keys to other rooms. Can every room be visited? (DFS over keys.) python def canvisitall(rooms)…
- Problem: Traverse a small directed graph (adjacency lists in the order shown) from node 0, once with recursive DFS and once with BFS…