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?- A. 2 1 2
- B. 2 0 2
- C. 2 1 3
- 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
- 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…
- Problem: Values are pushed one by one into Python's heapq (a binary min-heap stored in a list), then one value is popped. python import…