Data Structures & AlgorithmsVery hardProduct company OA
Binary lifting for lowest common ancestors (up[k][v] is the 2ᵏ-th ancestor; the root is its own parent). What is printed?
Binary lifting for lowest common ancestors (up[k][v] is the 2ᵏ-th ancestor; the root is its own parent). What is printed?
LOG = 4
par = {1: 1, 2: 1, 3: 1, 4: 2, 5: 2, 6: 3, 7: 4, 8: 4, 9: 7, 10: 9, 11: 6}
depth = {1: 0}
for v in sorted(par):
if v != 1: depth[v] = depth[par[v]] + 1
up = [{v: par[v] for v in par}]
for k in range(1, LOG): up.append({v: up[k - 1][up[k - 1][v]] for v in par})
def lca(a, b):
if depth[a] < depth[b]: a, b = b, a
d = depth[a] - depth[b]
for k in range(LOG):
if d >> k & 1: a = up[k][a]
if a == b: return a
for k in range(LOG - 1, -1, -1):
if up[k][a] != up[k][b]: a, b = up[k][a], up[k][b]
return up[0][a]
print(lca(10, 8), lca(10, 5), lca(11, 9), up[2][10], depth[10] + depth[11] - 2 * depth[lca(10, 11)])- A. 4 1 1 4 6
- B. 4 2 3 2 8
- C. 4 2 1 2 8
- D. 7 2 1 2 7
Correct answer: C. 4 2 1 2 8
Lift the deeper node by the depth difference using its binary digits, then lift both nodes together by decreasing powers while their ancestors differ. Paths: 10 → 9 → 7 → 4 → 2 → 1 and 11 → 6 → 3 → 1. lca(10, 8) = 4, lca(10, 5) = 2, lca(11, 9) = 1; up[2][10] is the 4th ancestor of 10 = 2; dist(10, 11) = 5 + 3 − 2·0 = 8. Preprocessing O(n log n), each query O(log n).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Brute force over all 4-edge subsets of a 5-vertex weighted graph with repeated weights. What is printed (MST weight, number of distinct…
- Floyd–Warshall with the correct loop order (k outermost) and with k innermost. What is printed (d[0][1], d[2][0], d[0][3] for each)?…
- Tarjan's SCC algorithm, then the condensation DAG. What is printed (SCCs, source components, sink components, minimum edges to add to make…
- Centroid of a tree: the vertex whose removal leaves the largest remaining component as small as possible. What is printed (centroid(s)…
- Assignment problem (worker i → distinct job) by DP over bitmasks of used jobs, versus row-by-row greedy. What is printed (optimal cost…
- Recursive segment tree with children 2·node and 2·node + 1: the largest array index actually used for a given n. What is printed? python…