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.

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

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
tree DP
rerooting
subtree size
DFS
post-order traversal
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 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 Problems
Sample Answer
Requirements
  • Input: n, edges forming a tree.
  • Output: list of length n with sum of distances from each node.
  • n up to about 3×1043 \times 10^4, 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...


Submit Your Answer
Markdown supported