Sum of Distances in Tree - Complete Solution Guide
Sum of Distances in Tree is LeetCode problem 834, a Hard level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given the integer n and the array edges where edges[i] = [a i , b i ] indicates that there is an edge between nodes a i and b i in the tree. Return an array answer of length n where answer[i] is the sum of the distances between the i th node in the tree and all other nodes. Example 1: Input: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]] Output: [8,12,6,10,10,10] Explanation: The tree is shown abo
Detailed Explanation
The problem asks us to calculate the sum of distances between each node in a given undirected tree and all other nodes. For each node `i`, we need to find the sum of the shortest path lengths from node `i` to every other node in the tree. The input consists of the number of nodes `n` and a list of edges representing the tree's connections. The output should be an array `answer` of length `n`, where `answer[i]` is the sum of distances from node `i` to all other nodes.
Solution Approach
The solution uses a two-pass Depth-First Search (DFS) algorithm to efficiently calculate the sum of distances for each node. The first DFS calculates the sum of distances from an arbitrary root node (node 0) and the number of nodes in each subtree. The second DFS propagates this information to calculate the sum of distances for all other nodes. This approach avoids calculating distances from scratch for each node.
Step-by-Step Algorithm
- Step 1: Build the graph representation from the given edges. Use an adjacency list where each node stores a list of its neighbors.
- Step 2: Initialize two arrays, `count` and `ans`, of size `n`. `count[i]` will store the number of nodes in the subtree rooted at node `i` (including node `i` itself). `ans[i]` will store the sum of distances from node `i` to all other nodes. Initialize `count[i]` to 1 for all nodes, and `ans[i]` to 0.
- Step 3: Perform the first DFS (dfs1) starting from an arbitrary root (node 0). During this DFS, calculate the `count` and `ans` arrays. For each node `u`, recursively calculate the `count` and `ans` values for its children. Update `count[u]` by adding the `count` values of its children. Update `ans[u]` by adding the `ans` values of its children plus the `count` of each child (representing the distance increase for each node in the child's subtree).
- Step 4: Perform the second DFS (dfs2) starting from the root node (node 0). During this DFS, propagate the sum of distances to all other nodes. For each node `u` and its child `v`, the sum of distances for `v` can be calculated as `ans[v] = ans[u] + n - 2 * count[v]`. This formula comes from the fact that when moving from `u` to `v`, the distances to nodes in `v`'s subtree decrease by 1 (count[v] nodes), and the distances to the other nodes increase by 1 (n - count[v] nodes).
- Step 5: Return the `ans` array, which contains the sum of distances for each node.
Key Insights
- Insight 1: Directly calculating distances from each node using BFS or DFS for every node would be O(n^2), which is too slow for the given constraints (n <= 3 * 10^4). We need a more efficient approach.
- Insight 2: The problem can be solved using dynamic programming and two Depth-First Searches (DFS). The first DFS calculates the sum of distances from an arbitrary root node (e.g., node 0) and the number of nodes in each subtree. The second DFS leverages this information to calculate the sum of distances for all other nodes by propagating information down the tree.
- Insight 3: The key idea is to realize that when moving from a parent node `u` to a child node `v`, the distances to all nodes in the subtree rooted at `v` decrease by 1, and the distances to all other nodes (n - count[v]) increase by 1. This allows us to efficiently update the sum of distances.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(n)
Topics
This problem involves: Dynamic Programming, Tree, Depth-First Search, Graph.
Companies
Asked at: ByteDance, MathWorks, Media.net, PhonePe.