Sum of distances in tree
Given an undirected tree with n nodes labeled 0..n-1 and its edge list, return an array res where res[i] is the sum of the distances from node i to every other node. A naive BFS from each node is O(n^2); instead use the rerooting technique: one post-order pass computes subtree sizes and the answer for the root, then one pre-order pass propagates each node's answer to its children in O(1) using res[child] = res[parent] - size[child] + (n - size[child]). Return res. n can be up to 3e4.
Implement
sum_of_distances(n: int, edges: list[list[int]]) → list[int]Examples
in
[6,[[0,1],[0,2],[2,3],[2,4],[2,5]]]out[8,12,6,10,10,10]What a strong answer looks like
State your approach and its time/space complexity out loud before you optimize. Handle the edge cases (empty input, duplicates, overflow), and say why you chose this over the brute force. Green tests are the floor, not the grade.
0:00 of about 40 min
solution.py
InputExpectedGot
[6,[[0,1],[0,2],[2,3],[2,4],[2,5]]][8,12,6,10,10,10]not run yetsample