Total Hop Distance From Every Node to All Others in a Tree
Last updated: November 29, 2026
Quick Overview
Given an undirected tree with n nodes, return an array where answer[i] is the sum of distances from node i to every other node.
0
0
0 solved
Given an undirected tree with n nodes, return an array where answer[i] is the sum of distances from node i to every other node.
A Google onsite question about rerooting, useful for picking a server location that minimizes total latency in a tree-shaped network. Running BFS from each node is O(n^2); the interviewer wants two DFS passes and the reasoning behind the rerooting formula.
What the Interviewer Expects
- Compute subtree sizes and the answer for one root in a first pass
- Derive the rerooting formula answer[child] = answer[parent] - size[child] + (n - size[child])
- Propagate answers in a second pass
- Write both passes iteratively
- Explain the formula intuitively
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 edges have weights?
- Find the node with the minimum total distance (the tree median).
- Support adding a leaf and updating all answers.
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:
n,edgesforming a tree. - Output: list of length
nwith sum of distances from each node. - n up to about , so quadratic is too slow....
High-Level Design
Pass 1 (post-order from root 0): compute size[v] (nodes in v's subtree) and answer[0] as the sum of depths, which can be accumulated as dist[v] = sum(dist[c] + size[c]) over children.
Pass 2 (p...