Sum of Distances in Tree
Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.
Practice this as a mock interviewFree to start, no account neededProblem
You are given an undirected, connected tree with n nodes labeled 0 to n - 1 and n - 1 edges, where edges[i] = [a, b] joins nodes a and b.
Return an array answer of length n in which answer[i] is the sum of the distances (number of edges on the shortest path) from node i to every other node in the tree.
Running a BFS from every node costs O(n^2), which is too slow for the largest inputs. Solve it in O(n) by rerooting: compute subtree sizes and the answer for one root, then derive each child's answer from its parent's.
Examples
Constraints
- 1 <= n <= 3 * 10^4
- edges.length == n - 1
- edges[i].length == 2
- 0 <= a, b < n and a != b
- The edges form a valid tree
What the interviewer grades
A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.