My first instinct was brute force BFS from every node, which is O(N^2) and works for small inputs but N can be 3*10^4 so that's not going to cut it.
Use a two-pass tree DP (rerooting technique): first compute subtree sizes and the sum of distances from the root via a post-order DFS, then propagate the answer to all nodes via a pre-order DFS using the relation ans[child] = ans[parent] + N - 2 * subtree_size[child]. This achieves O(N) time and O(N) space, which is optimal.
Pro tip: Mention that the rerooting recurrence is derived by observing that moving the root from parent to child decreases distances to the child's subtree by 1 and increases distances to all other nodes by 1, yielding the formula. This shows deep understanding and avoids brute-force O(N^2).
Confirm the tree is connected, undirected, and has N-1 edges. Define the output array ans[i] as the sum of distances from node i to all other nodes.
Root the tree at node 0. Perform a post-order DFS to compute subtree sizes (sub[i]) and the sum of distances from the root to all nodes (ans[0]).
Perform a pre-order DFS. For each child v of u, compute ans[v] = ans[u] + N - 2 * sub[v]. This propagates the answer to all nodes.
After the second DFS, ans array contains the required sums for all nodes. Return it.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.