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?- A. [12, 17, 9, 14, 10, 15, 15] 4
- B. [12, 18, 10, 14, 10, 16, 16] 2
- C. [11, 17, 9, 13, 10, 15, 15] 2
- 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
- Problem: Count integers in [1, N] divisible by at least one of the given numbers using inclusion–exclusion with LCMs (N up to 10⁹, so no…
- Problem: Compute C(n, r) mod a SMALL prime p = 7 when n ≥ p: Lucas' theorem versus factorials with Fermat inverses. python p = 7 fact =…
- Problem: Count ways to climb n stairs with steps of 1 or 3, modulo 10⁹ + 7, using a 3 × 3 matrix power so that n up to 10¹⁸ is fine…
- Problem: Peak number of simultaneous bookings with a sweep line. In the first call intervals are CLOSED [s, e] (a booking ending at 3 and…
- Problem: Total length covered by a set of intervals, and the length covered by EXACTLY one interval, using coordinate compression and a…
- Problem: Warehouses at positions a with daily shipments w; choose a hub position x minimising Σ wᵢ·|aᵢ − x|. Compare the weighted median…