Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA
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 has exactly one coin: each edge carries |excess of the subtree below it|. Trees are built from a level-order list by build(xs) (None = missing child), shown in the code.
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 has exactly one coin: each edge carries |excess of the subtree below it|. 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 coin_moves(root):
moves = 0
def go(t):
nonlocal moves
if not t: return 0
l, r = go(t.l), go(t.r)
moves += abs(l) + abs(r)
return t.v + l + r - 1
go(root)
return moves
print(coin_moves(build([0, 4, 0, None, None, 0])), coin_moves(build([1, 0, 2])))What is printed?- A. 4 2
- B. 3 2
- C. 6 1
- D. 6 2
Correct answer: D. 6 2
go returns a subtree's excess (coins − nodes); exactly that many coins must cross the edge to the parent, in one direction or the other. First tree: root 0 → (4, 0), right 0 → (0, –). The left leaf sends 3 up (3), the right child's subtree needs 2 (2 moves across the root's right edge), and its own left child needs 1 more (1) → 6. Second: 2 sends 1 to the root and the root sends 1 to the left → 2. O(n).
More Coding Interview Problems questions
- 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…
- Problem: Each element of a log is at most k = 2 positions away from its sorted position. Sort it with a min-heap of size k + 1. python…