You are on page 1of 8

COL106: Data Structures and

Algorithms

Lowest Common Ancestor 



Oracle

Keerti Choudhary
Department of Computer Science, IIT Delhi
Lowest Common Ancestor

De nition: For any two vertices x and y in a tree T rooted at source s, the

Lowest-Common-Ancestor of x, y a.k.a. LCA(x, y) is that common ancestor
of x and y that is farthest from s.



Example:
S
0

A B C
1

D F H I J 2

LCA(P,Q)
K L M N 3

O P Q 4
fi
Lowest Common Ancestor

De nition: For any two vertices x and y in a tree T rooted at source s, the

Lowest-Common-Ancestor of x, y a.k.a. LCA(x, y) is that common ancestor
of x and y that is farthest from s.



Example:
S
0

LCA(K,F) 1
A B C

D F H I J 2

K L M N 3

O P Q 4
fi
Lowest Common Ancestor

De nition: For any two vertices x and y in a tree T rooted at source s, the

Lowest-Common-Ancestor of x, y a.k.a. LCA(x, y) is that common ancestor
of x and y that is farthest from s.



Example:
LCA(L,Q)
S
0

A B C
1

D F H I J 2

K L M N 3

O P Q 4
fi
LCA Oracle

Problem: Goal is to pre-process a rooted tree T with n vertices to compute a


data-structure so that:



— For any x and y, can report LCA(x, y) in O(log n) time.



— Time to compute data-structure is O(n log n).

𝒟
𝒟
𝒟
LCA Oracle Construction S

A(X, 3)

Data-Structure: For each x ∈ T and i ⩽ log2 n



we only store:


A(x, i):= An ancestor r of x satisfying 


level(x) − level(r) = 2i.

A(X, 2)

A(X, 1)
Values A(x, i) can be computed in top-down
manner in a total of O(n log n) time as 
 A(X, 0)

A(x, i + 1) = A(y, i), where y = A(x, i) X
S
Answering Query

W
Step 1: Suppose level(x) ⩾ level(y), then in
O(log n) time nd an ancestor ‘z’ of x such that


level(z) = level(y)

A(J, 1) Z Y

Algorithm to nd z:


Represent | level(x) − level(y) | as sum of 
 J A(X, 2)
powers of 2, and take hops according to these 

powers.


Example: if level di erence is 6 = 22 + 21,

then rst hop is of 22 and second hop is 21.

X
fi
fi
fi
ff
S
Answering Query

Parent(Y’’)
W
Step 2: Given y, z satisfying level(y) = level(z),
we will compute LCA(y, z) in O(log n) time.
 A(Y’, 1) Y’’ Z’’

Algorithm to nd LCA(y, z):
 A(Y, 3) Y’ Z’



 10 =
0. If y = z then return y 
 23 + 21


1. Set y0 = y, z0 = z


2. For i = log2 n to 0 do:


If A(y0, i) ≠ A(z0, i) then

Set y0 = A(y0, i)

Set z0 = A(z0, i)


3. Return Parent(y0)

Y Z
fi

You might also like