Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Answer lowest-common-ancestor queries with binary lifting (up[j][v] = 2^j-th ancestor).

Problem: Answer lowest-common-ancestor queries with binary lifting (up[j][v] = 2^j-th ancestor).
par = [-1, 0, 0, 1, 1, 2, 3, 3, 4, 5, 9]
n, LOG = len(par), 4
depth = [0] * n
for v in range(1, n): depth[v] = depth[par[v]] + 1
up = [[p if p >= 0 else 0 for p in par]]
for j in range(1, LOG): up.append([up[j-1][up[j-1][v]] for v in range(n)])
def lca(a, b):
    if depth[a] < depth[b]: a, b = b, a
    for j in range(LOG - 1, -1, -1):
        if depth[a] - (1 << j) >= depth[b]: a = up[j][a]
    if a == b: return a
    for j in range(LOG - 1, -1, -1):
        if up[j][a] != up[j][b]: a, b = up[j][a], up[j][b]
    return par[a]
print(lca(6, 8), lca(10, 7), lca(7, 6))
What is printed?
  1. A. 3 0 1
  2. B. 1 2 3
  3. C. 1 0 3
  4. D. 4 0 3

Correct answer: C. 1 0 3

Node 6 and 8 hang under 3 and 4, both children of 1, so LCA = 1. Node 10's chain is 10 → 9 → 5 → 2 → 0 and 7's is 7 → 3 → 1 → 0, so they meet at the root 0. 6 and 7 are siblings under 3.

More Coding Interview Problems questions

Exams that ask this topic