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?
  1. A. 4 2
  2. B. 3 2
  3. C. 6 1
  4. 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

Exams that ask this topic