Question
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.
sum_of_distances(n: int, edges: list[list[int]]) → list[int][6,[[0,1],[0,2],[2,3],[2,4],[2,5]]]out[8,12,6,10,10,10]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.
Vibe coding: describe the solution in plain language (or narrate it) and the coach grades your approach. Generating runnable code from your description is coming next.