Code RoomTree distance sum rerooting
HardPrep Room Coding #1281

Tree distance sum rerooting

CodingDatabases & SQLAlgorithms & data structuresSenior–Staff~35 min

Given a tree with n nodes (0..n-1) described by an edge list, return an array res where res[v] is the sum of distances from node v to every other node. Use rerooting (two DFS passes) so the whole answer is computed in O(n). Constraints: 1 <= n <= 30000; the input is a connected undirected tree given as n and a list of [u, v] edges.

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 35 min
InputExpectedGot
[6,[[0,1],[0,2],[2,3],[2,4],[2,5]]][8,12,6,10,10,10]not run yetsample