Data Structures & AlgorithmsVery hardProduct company OA

Problem: Place the minimum number of cameras on tree nodes so every node is monitored (a camera covers itself, its parent and its children). Post-order states: 0 = not covered, 1 = has camera, 2 = covered. Trees are built from a level-order list by build(xs) (None = missing child), shown in the code.

Problem: Place the minimum number of cameras on tree nodes so every node is monitored (a camera covers itself, its parent and its children). Post-order states: 0 = not covered, 1 = has camera, 2 = covered. 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 cameras(root):
    cnt = 0
    def go(t):
        nonlocal cnt
        if not t: return 2
        l, r = go(t.l), go(t.r)
        if l == 0 or r == 0: cnt += 1; return 1
        return 2 if l == 1 or r == 1 else 0
    if go(root) == 0: cnt += 1
    return cnt
print(cameras(build([0, 0, 0, None, 0, None, 0, 0])), cameras(build([0])), cameras(build([0] * 7)))
What is printed?
  1. A. 2 1 2
  2. B. 2 0 2
  3. C. 2 1 3
  4. D. 3 1 2

Correct answer: A. 2 1 2

Greedy from the leaves: never put a camera on a leaf; put one on the parent of any uncovered child; a node next to a camera is covered; an uncovered root needs its own. First tree: two chains root–A–C–E and root–B–D; cameras on C (covers A, E) and B (covers root, D) → 2. A single node needs 1 (the final root check). A perfect 7-node tree: cameras on both middle nodes → 2. Missing the final root check would give 0 for [0]. O(n).

More Coding Interview Problems questions

Exams that ask this topic