Data Structures & AlgorithmsVery hardProduct company OA

Problem: For every warehouse in a tree network, compute the sum of distances to all other warehouses with two passes (rerooting): ans[child] = ans[parent] − size[child] + (n − size[child]).

Problem: For every warehouse in a tree network, compute the sum of distances to all other warehouses with two passes (rerooting): ans[child] = ans[parent] − size[child] + (n − size[child]).
n = 7
edges = [(0, 1), (0, 2), (2, 3), (2, 4), (4, 5), (4, 6)]
adj = [[] for _ in range(n)]
for a, b in edges: adj[a].append(b); adj[b].append(a)
order, par = [0], [-1] * n
for u in order:
    for v in adj[u]:
        if v != par[u]: par[v] = u; order.append(v)
size = [1] * n; down = [0] * n
for u in reversed(order):
    for v in adj[u]:
        if v != par[u]: size[u] += size[v]; down[u] += down[v] + size[v]
ans = [0] * n; ans[0] = down[0]
for u in order:
    for v in adj[u]:
        if v != par[u]: ans[v] = ans[u] - size[v] + (n - size[v])
print(ans, min(range(n), key=lambda i: ans[i]))
What is printed?
  1. A. [12, 17, 9, 14, 10, 15, 15] 4
  2. B. [12, 18, 10, 14, 10, 16, 16] 2
  3. C. [11, 17, 9, 13, 10, 15, 15] 2
  4. D. [12, 17, 9, 14, 10, 15, 15] 2

Correct answer: D. [12, 17, 9, 14, 10, 15, 15] 2

First pass: subtree sizes and the distance sum from root 0 (12). Moving the root from u to its child v brings the size[v] nodes of v's subtree one step closer and the other n − size[v] one step farther. Vertex 2 (the hub joining 0, 3 and 4) is best with 9. Recomputing BFS from every node would be O(n²); rerooting is O(n).

More Coding Interview Problems questions

Exams that ask this topic