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?- A. [16, 11, 16, 9, 14, 12, 17]
- B. [15, 10, 15, 10, 15, 13, 19]
- C. [16, 10, 15, 10, 15, 12, 17]
- 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
- Problem: Walk along buildings; climbing up by d costs d bricks or one ladder (going down is free). Use ladders on the largest climbs (a…
- Problem: Return the k pairs (u from a, v from b) with the smallest sums, using a heap seeded with (a[i], b[0]). python import heapq def…
- Problem: Median of two sorted arrays in O(log(min(m, n))) by binary searching the partition of the shorter array. python def median(a, b)…
- Problem: Find the k-th positive integer missing from a strictly increasing array, by binary search on 'missing before index i' = a[i] − (i…
- Problem: Find the area of the largest square of 1s in a binary matrix. python def square(m): R, C = len(m), len(m[0]); dp = [[0] (C + 1)…
- Problem: Length of the longest common CONTIGUOUS subarray of two arrays (DP on suffix matches). python def common(a, b): dp = [[0] (len(b)…