Hiring process8 levels
  1. 1 IQ Test
  2. 2 Additional Online Test (If Required)
  3. 3 Office Interview with Hiring Manager
  4. 4 Unpaid Test Task (Motivation Check)
  5. 5 Paid Test Task and Follow-Up Interview
  6. 6 Iterative Paid Test Tasks
  7. 7 Office Verification
  8. 8 Final Interview with the Founder

Problems > Everyone's Total Commute > Editorial

Everyone's Total Commute — Solution & Editorial

Back to the Problem

Rerooting: one post-order pass computes subtree sizes and the root's answer; then moving the root across an edge changes the sum by (N − 2·size[child]) — a second pre-order pass yields every node in O(1) each.

Complexity: O(N)

Watch out: The transition ans[c] = ans[p] − size[c] + (N − size[c]) — both terms, both signs.