← Back to experiences
[ OK ] Loaded —
[ INFO ]
$ cd
$ ls -lt
01
02
03
04
05
$ ls -lt
01
02
03
04
05
user@intervues:~/experiences/…$
Level: Unknown Level
Round: Phone Screen · Type: Coding · Difficulty: 6/10 · Duration: 60 min · Interviewer: Unfriendly
Topics: Tree Traversal, Depth-First Search (DFS), Breadth-First Search (BFS), Dynamic Programming, Re-rooting
Location: Mountain View, CA
Interview date: 2025-12-31
I was asked to find the sum of distances from each node to all other nodes in a given tree.
The coding question I received was:
Given a tree, calculate the sum of the distances from each node to all other nodes.
My Approach:
Baseline (Non-Optimal):
Optimal Solution (Reroot DP, Two DFS):
sub[u] = size of the subtree rooted at udp[u] = sum of distances from all nodes in the subtree rooted at u to udp[u] += dp[v] + sub[v] (because all nodes in subtree v are 1 unit further from u than from v)ans[0] = dp[0].sub[v] nodes in v's subtree are 1 unit closer, and the remaining n-sub[v] nodes are 1 unit further.ans[v] = ans[u] - sub[v] + (n - sub[v]) = ans[u] + n - 2*sub[v]Key Insights:
LeetCode similar: LeetCode 834