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)])
  1. A. 4 1 1 4 6
  2. B. 4 2 3 2 8
  3. C. 4 2 1 2 8
  4. 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).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic