Fewest Moves to Leave Exactly One Replica on Every Node

Last updated: November 29, 2026

Quick Overview

A binary tree of storage nodes holds n replicas in total across n nodes, distributed unevenly. In one move a replica moves across one edge. Return the minimum number of moves so every node holds exactly one.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

0

0

0 solved


A binary tree of storage nodes holds n replicas in total across n nodes, distributed unevenly. In one move a replica moves across one edge. Return the minimum number of moves so every node holds exactly one.

A Google onsite question about rebalancing data across a hierarchy. The insight interviewers look for is that each edge carries a fixed net flow equal to the surplus or deficit of the subtree below it.

What the Interviewer Expects
  • Define a subtree's excess as replicas minus nodes
  • Observe that excess must cross the edge to the parent
  • Sum absolute excesses over all edges
  • Compute in one post-order pass
  • Argue why this is a lower bound and achievable
Key Topics to Cover
binary trees
post-order traversal
flow on trees
greedy argument
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • What if each node needs a different target count?
  • Return the actual sequence of moves.
  • How does this change on a general tree or a graph?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input: root where node.val is the replica count, with total replicas equal to the node count. Output: minimum number of single-edge moves. Moves can go up or down....

High-Level Design

For a subtree S, define excess(S) = replicas in S - nodes in S. Whatever the plan, exactly |excess(S)| replicas must cross the edge between S and its parent, either out (positive) or in (negative)...


Submit Your Answer
Markdown supported