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?- A. 3 0 1
- B. 1 2 3
- C. 1 0 3
- 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
- A COMPLETE binary tree has n nodes. Counting them by comparing the leftmost and rightmost depths at each node and recursing into only one…
- Problem: Rebuild a BST from its preorder traversal (using value bounds) and print its postorder. python def postfrompre(pre): i, out = 0…
- 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] −…
- 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)…