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] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.
Return an array answer of length n where answer[i] is the sum of the distances between the ith 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 above.
We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
equals 1 + 1 + 2 + 2 + 2 = 8.
Hence, answer[0] = 8, and so on.
Problem summary: 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] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. Return an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming · Tree
Example 1
6
[[0,1],[0,2],[2,3],[2,4],[2,5]]
Example 2
1
[]
Example 3
2
[[1,0]]
Related Problems
Distribute Coins in Binary Tree (distribute-coins-in-binary-tree)
Count Nodes With the Highest Score (count-nodes-with-the-highest-score)
Collect Coins in a Tree (collect-coins-in-a-tree)
Maximum Score After Applying Operations on a Tree (maximum-score-after-applying-operations-on-a-tree)
Count Pairs of Connectable Servers in a Weighted Tree Network (count-pairs-of-connectable-servers-in-a-weighted-tree-network)
Step 02
Core Insight
What unlocks the optimal approach
No official hints in dataset. Start from constraints and look for a monotonic or reusable state.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #834: Sum of Distances in Tree
class Solution {
private int n;
private int[] ans;
private int[] size;
private List<Integer>[] g;
public int[] sumOfDistancesInTree(int n, int[][] edges) {
this.n = n;
g = new List[n];
ans = new int[n];
size = new int[n];
Arrays.setAll(g, k -> new ArrayList<>());
for (var e : edges) {
int a = e[0], b = e[1];
g[a].add(b);
g[b].add(a);
}
dfs1(0, -1, 0);
dfs2(0, -1, ans[0]);
return ans;
}
private void dfs1(int i, int fa, int d) {
ans[0] += d;
size[i] = 1;
for (int j : g[i]) {
if (j != fa) {
dfs1(j, i, d + 1);
size[i] += size[j];
}
}
}
private void dfs2(int i, int fa, int t) {
ans[i] = t;
for (int j : g[i]) {
if (j != fa) {
dfs2(j, i, t - size[j] + n - size[j]);
}
}
}
}
// Accepted solution for LeetCode #834: Sum of Distances in Tree
func sumOfDistancesInTree(n int, edges [][]int) []int {
g := make([][]int, n)
for _, e := range edges {
a, b := e[0], e[1]
g[a] = append(g[a], b)
g[b] = append(g[b], a)
}
ans := make([]int, n)
size := make([]int, n)
var dfs1 func(i, fa, d int)
dfs1 = func(i, fa, d int) {
ans[0] += d
size[i] = 1
for _, j := range g[i] {
if j != fa {
dfs1(j, i, d+1)
size[i] += size[j]
}
}
}
var dfs2 func(i, fa, t int)
dfs2 = func(i, fa, t int) {
ans[i] = t
for _, j := range g[i] {
if j != fa {
dfs2(j, i, t-size[j]+n-size[j])
}
}
}
dfs1(0, -1, 0)
dfs2(0, -1, ans[0])
return ans
}
# Accepted solution for LeetCode #834: Sum of Distances in Tree
class Solution:
def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:
def dfs1(i: int, fa: int, d: int):
ans[0] += d
size[i] = 1
for j in g[i]:
if j != fa:
dfs1(j, i, d + 1)
size[i] += size[j]
def dfs2(i: int, fa: int, t: int):
ans[i] = t
for j in g[i]:
if j != fa:
dfs2(j, i, t - size[j] + n - size[j])
g = defaultdict(list)
for a, b in edges:
g[a].append(b)
g[b].append(a)
ans = [0] * n
size = [0] * n
dfs1(0, -1, 0)
dfs2(0, -1, ans[0])
return ans
// Accepted solution for LeetCode #834: Sum of Distances in Tree
/**
* [0834] Sum of Distances in Tree
*
* 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] = [ai, bi] indicates that there is an edge between nodes ai and bi 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:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist1.jpg" style="width: 304px; height: 224px;" />
* 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 above.
* We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
* equals 1 + 1 + 2 + 2 + 2 = 8.
* Hence, answer[0] = 8, and so on.
*
* Example 2:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist2.jpg" style="width: 64px; height: 65px;" />
* Input: n = 1, edges = []
* Output: [0]
*
* Example 3:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist3.jpg" style="width: 144px; height: 145px;" />
* Input: n = 2, edges = [[1,0]]
* Output: [1,1]
*
*
* Constraints:
*
* 1 <= n <= 3 * 10^4
* edges.length == n - 1
* edges[i].length == 2
* 0 <= ai, bi < n
* ai != bi
* The given input represents a valid tree.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/sum-of-distances-in-tree/
// discuss: https://leetcode.com/problems/sum-of-distances-in-tree/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
// Credit: https://leetcode.com/problems/sum-of-distances-in-tree/discuss/892069/Rust-translated-8ms-100
pub fn sum_of_distances_in_tree(n: i32, edges: Vec<Vec<i32>>) -> Vec<i32> {
let mut tree = vec![std::collections::HashSet::<i32>::new(); n as usize];
let mut result = vec![0; n as usize];
let mut count = vec![0; n as usize];
for edge in &edges {
tree[edge[0] as usize].insert(edge[1]);
tree[edge[1] as usize].insert(edge[0]);
}
Self::dfs(&tree, &mut count, &mut result, 0, -1);
Self::dfs2(&tree, &mut count, &mut result, 0, -1);
result
}
fn dfs(
tree: &[std::collections::HashSet<i32>],
count: &mut Vec<i32>,
result: &mut Vec<i32>,
root: i32,
pre: i32,
) {
for &i in &tree[root as usize] {
if i == pre {
continue;
}
Self::dfs(tree, count, result, i, root);
count[root as usize] += count[i as usize];
result[root as usize] += result[i as usize] + count[i as usize];
}
count[root as usize] += 1;
}
fn dfs2(
tree: &[std::collections::HashSet<i32>],
count: &mut Vec<i32>,
result: &mut Vec<i32>,
root: i32,
pre: i32,
) {
for &i in &tree[root as usize] {
if i == pre {
continue;
}
result[i as usize] =
result[root as usize] - count[i as usize] + count.len() as i32 - count[i as usize];
Self::dfs2(tree, count, result, i, root);
}
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_0834_example_1() {
let n = 6;
let edges = vec![vec![0, 1], vec![0, 2], vec![2, 3], vec![2, 4], vec![2, 5]];
let result = vec![8, 12, 6, 10, 10, 10];
assert_eq!(Solution::sum_of_distances_in_tree(n, edges), result);
}
#[test]
fn test_0834_example_2() {
let n = 1;
let edges: Vec<Vec<i32>> = vec![];
let result = vec![0];
assert_eq!(Solution::sum_of_distances_in_tree(n, edges), result);
}
#[test]
fn test_0834_example_3() {
let n = 2;
let edges: Vec<Vec<i32>> = vec![vec![1, 0]];
let result = vec![1, 1];
assert_eq!(Solution::sum_of_distances_in_tree(n, edges), result);
}
}
// Accepted solution for LeetCode #834: Sum of Distances in Tree
function sumOfDistancesInTree(n: number, edges: number[][]): number[] {
const g: number[][] = Array.from({ length: n }, () => []);
for (const [a, b] of edges) {
g[a].push(b);
g[b].push(a);
}
const ans: number[] = new Array(n).fill(0);
const size: number[] = new Array(n).fill(0);
const dfs1 = (i: number, fa: number, d: number) => {
ans[0] += d;
size[i] = 1;
for (const j of g[i]) {
if (j !== fa) {
dfs1(j, i, d + 1);
size[i] += size[j];
}
}
};
const dfs2 = (i: number, fa: number, t: number) => {
ans[i] = t;
for (const j of g[i]) {
if (j !== fa) {
dfs2(j, i, t - size[j] + n - size[j]);
}
}
};
dfs1(0, -1, 0);
dfs2(0, -1, ans[0]);
return ans;
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n)
Space
O(n)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Forgetting null/base-case handling
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.