Compute distance-sum from every tree node
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of tree and graph algorithms, including computation of pairwise distances and techniques for aggregating path lengths across nodes.
Constraints
- 1 <= n <= 2 * 10^5
- edges.length == n - 1
- 0 <= u, v < n
- The input graph is a tree: connected and acyclic
- The answer for a node can exceed 32-bit signed integer range, so use 64-bit integers in fixed-width languages
Examples
Input: (1, [])
Expected Output: [0]
Explanation: A tree with one node has no other nodes to reach, so the distance sum is 0.
Input: (4, [[0, 1], [1, 2], [1, 3]])
Expected Output: [5, 3, 5, 5]
Explanation: From node 1, distances to 0, 2, and 3 are 1, 1, and 1, so the sum is 3. Each leaf has total distance 5.
Input: (5, [[0, 1], [0, 2], [0, 3], [0, 4]])
Expected Output: [4, 7, 7, 7, 7]
Explanation: Node 0 is connected directly to all others, so its sum is 4. Any leaf is distance 1 from node 0 and distance 2 from the other three leaves, giving 1 + 2 + 2 + 2 = 7.
Input: (6, [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]])
Expected Output: [15, 11, 9, 9, 11, 15]
Explanation: This is a straight line. Middle nodes have the smallest distance sums, and symmetric positions have equal answers.
Hints
- Root the tree at any node, such as 0. In one traversal, compute each node's depth and the size of every subtree.
- If you know the answer for node u, then for a child v: moving the root from u to v makes all nodes in v's subtree 1 closer and all other nodes 1 farther.