Sum of Distances in Tree
Reported by candidates from Google's online assessment. Pattern, common pitfall, and the honest play if you blank under the timer.
The mistake that sinks a first attempt on this one is running a BFS from every node. Google reported Sum of Distances in Tree in September 2024, and with n up to 30000 that O(n^2) approach times out the moment the tests get big. The real answer is tree rerooting: two DFS passes, linear time. If you've got the invite and 48 hours, learn the reroot formula and nothing else. StealthCoder sits invisible on your screen during the live OA as a safety net if the formula slips out of your head mid-test.
The problem
You are given a connected undirected tree with n nodes numbered from 0 to n - 1. The array edges contains the tree's n - 1 edges. Return an integer array answer of length n, where answer[u] is the sum of the shortest-path distances from node u to every other node. Function sumOfDistancesInTree(n: int, edges: int[][]) → int[] Examples Example 1 n = 6 edges = [[0,1],[0,2],[2,3],[2,4],[2,5]] return = [8,12,6,10,10,10] From node 0, the distances are 0, 1, 1, 2, 2, 2, which sum to 8. Repeating the definition for each root gives the returned array. Example 2 n = 1 edges = [] return = [0] The only node has distance 0 to itself. Constraints 1 <= n <= 30000 edges.length = n - 1 Every row of edges is [u, v] with 0 <= u, v < n and u != v. edges forms one connected tree.
Reported by candidates. Source: FastPrep
Pattern and pitfall
The trick is rerooting. Pass one: root the tree at 0, compute count[u] (subtree size) and ans[0] (sum of depths) via DFS. Pass two: for each child c of parent p, ans[c] = ans[p] - count[c] + (n - count[c]). Moving the root from p to c brings count[c] nodes one step closer and pushes the other n - count[c] nodes one step farther. The common pitfall is the off-by-one in that formula, or using recursion on a 30000-node path-shaped tree and blowing the stack. Use an iterative DFS or raise the recursion limit. Also handle n = 1 returning [0]. Build an adjacency list, not a matrix. If you blank on the reroot step during the live OA, StealthCoder is the hedge: it reads the problem and hands you the two-pass solution without the proctor seeing it.
StealthCoder is the hedge for the one pattern you didn't drill. It runs invisibly during the screen share.
You can drill Sum of Distances in Tree cold, or you can hedge it. StealthCoder runs invisibly during screen share and surfaces a working solution in under 2 seconds. The proctor sees the IDE. They don't see what's behind it. If you're reading this with an OA window open, you're who this was built for.
Get StealthCoderRelated leaked OAs
This OA pattern shows up on LeetCode as sum of distances in tree. If you have time before the OA, drill that.
You've seen the question.
Make sure you actually pass Google's OA.
Google reuses patterns across OAs. If you're reading this with an OA window open, you're who this was built for. Works on HackerRank, CodeSignal, CoderPad, and Karat.
Sum of Distances in Tree FAQ
How hard is Sum of Distances in Tree really?+
It's a hard-tier problem, but only because the rerooting idea isn't obvious. Once you know it, the code is about 25 lines. The brute force is easy and wrong on time. The gap is seeing that answers for adjacent nodes are related by a simple formula.
What's the trick to solve it in linear time?+
Compute subtree sizes and the root's distance sum in one DFS. Then move the root across each edge. Going from parent p to child c, ans[c] = ans[p] - size[c] + (n - size[c]). Everything in c's subtree gets closer by one, everything else gets farther by one.
Why does the BFS-from-every-node approach fail?+
It costs O(n) per node, so O(n^2) total. With n up to 30000 that's around 900 million operations in the worst case, which is too slow for most judges. Rerooting drops it to O(n) with two passes.
Is the tree rerooting pattern still asked at Google?+
This one was reported for Google in September 2024, so yes, it's live. Rerooting shows up as a family: sum of distances, max distance per node, tree diameter variants. Learning the pattern covers several questions at once.
How do I prepare in 48 hours?+
Write this solution from scratch twice, iteratively, without looking. Then test n = 1, a line-shaped tree, and a star. Spend the rest of the time on subtree-size DFS basics. Don't try to cover all of tree DP. One pattern done well beats five done halfway.