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.
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
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- 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 ProblemsSample 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)...