Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Move the coins of a binary tree so every node has exactly one coin; a move passes one coin along one edge. Count the minimum moves.

Problem: Move the coins of a binary tree so every node has exactly one coin; a move passes one coin along one edge. Count the minimum moves.
class T:
    def __init__(s, v): s.v, s.l, s.r = v, None, None
def build(xs):
    nodes = [T(x) if x is not None else None for x in xs]
    kids = iter(nodes[1:])
    for nd in nodes:
        if nd:
            nd.l = next(kids, None); nd.r = next(kids, None)
    return nodes[0]
moves = 0
def excess(nd):
    global moves
    if not nd: return 0
    l, r = excess(nd.l), excess(nd.r)
    moves += abs(l) + abs(r)
    return nd.v + l + r - 1
excess(build([1, 0, 0, None, 3]))
print(moves)
What is printed?
  1. A. 3
  2. B. 4
  3. C. 5
  4. D. 2

Correct answer: B. 4

Tree: root 1 with children 0 and 0; the left child has a right child holding 3. That leaf has excess 2 (2 moves up its edge); the left child then has excess 0 − 1 + 2 = 1 (1 move to the root); the right child has excess −1 (1 move down to it). Each edge carries |excess| coins: 2 + 1 + 1 = 4.

More Coding Interview Problems questions

Exams that ask this topic