Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: For every node of a tree, compute the sum of distances to all other nodes in O(n) with re-rooting: ans[child] = ans[parent] − size[child] + (n − size[child]).

Problem: For every node of a tree, compute the sum of distances to all other nodes in O(n) with re-rooting: ans[child] = ans[parent] − size[child] + (n − size[child]).
n = 7
E = [(0, 1), (1, 2), (1, 3), (3, 4), (3, 5), (5, 6)]
g = [[] for _ in range(n)]
for u, v in E: g[u].append(v); g[v].append(u)
size, ans = [1] * n, [0] * n
def dfs1(u, p, d):
    ans[0] += d
    for v in g[u]:
        if v != p: dfs1(v, u, d + 1); size[u] += size[v]
def dfs2(u, p):
    for v in g[u]:
        if v != p:
            ans[v] = ans[u] - size[v] + (n - size[v]); dfs2(v, u)
dfs1(0, -1, 0); dfs2(0, -1)
print(ans)
What is printed?
  1. A. [16, 11, 16, 9, 14, 12, 17]
  2. B. [15, 10, 15, 10, 15, 13, 19]
  3. C. [16, 10, 15, 10, 15, 12, 17]
  4. D. [15, 10, 15, 9, 14, 12, 17]

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

Moving the root from parent to child brings size[child] nodes one step closer and pushes the other n − size[child] one step farther. Starting from ans[0] (computed by one DFS) a second DFS fills every node, matching a BFS from each node.

More Coding Interview Problems questions

Exams that ask this topic