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?- A. 3
- B. 4
- C. 5
- 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
- Problem: Find the maximum |a − b| where a is an ancestor of b in a binary tree. python class T: def init(s, v): s.v, s.l, s.r = v, None…
- Problem: Return the (1-based) level of a binary tree with the largest sum of values (smallest level on ties). python class T: def init(s…
- Problem: Every minute, fresh oranges (1) next to rotten ones (2) rot (4 directions). How many minutes until no fresh orange remains (−1 if…
- Problem: Find the path from node 0 to node 3 with the maximum product of edge success probabilities (Dijkstra on −log p, or a max-heap on…
- Problem: Each bus route is a loop of stops. Find the fewest buses needed to travel from stop S to stop T (BFS over routes, not stops)…
- Problem: Hire exactly K workers; each is paid in proportion to quality, and at least their minimum wage. Minimise total pay (sort by…