Graph Theory37 sections · 1633 units
Open in Course

Complexity Analysis (Linear time)

O(n) proof

Both DFS passes visit each node exactly once. The down pass computes size[v] and down[v] for all nn nodes. The up pass computes answer[v] for all nn nodes. Each pass is O(n)O(n) time.

Total time: O(n)O(n) for building the adjacency list, O(n)O(n) for the down pass, O(n)O(n) for the up pass. That gives O(n)O(n) overall.

Space: O(n)O(n) for the adjacency list, O(n)O(n) for the sizesize, downdown, and answeranswer arrays. Total space is O(n)O(n).

Compare this to the brute force O(n2)O(n^2) approach. For n=200,000n = 200{,}000, rerooting finishes in milliseconds while brute force would time out.