Lowest Common Ancestors
Binary lifting, Euler tours with range minimum, and Tarjan’s offline algorithm.
Which is the deepest node above both and ? Walking up from both answers in per query. Storing ancestors at power-of-two distances answers in ; writing the tree out as an Euler tour turns the question into a range minimum, answered in ; and after preprocessing, per query is optimal on the word RAM. On a pointer machine it is not achievable at all, and in the space an index needs, the Catalan numbers set the limit.
What you’ll learn
- Define lowest common ancestors and prove binary lifting correct, with preprocessing and queries for LCA and -th ancestors.
- Prove that the LCA is the shallowest node between the two first visits of an Euler tour, and answer queries in with a sparse table.
- Explain the block decomposition that gives preprocessing and queries, and the equivalence of LCA and RMQ through Cartesian trees.
- Prove Tarjan's offline algorithm correct, and state the lower bounds: per query on a pointer machine, and bits for an index-only RMQ structure.
The problem, and binary lifting
The naive method computes depths, lifts the deeper node until both have the same depth, then lifts both until they meet: , which is per query on a path. Binary lifting stores jumps instead of single steps. Let be the ancestor levels above , or the root if is not that deep. Then is the parent, and two jumps of make one of :
Any ancestor at distance is then reached by one jump per 1-bit of .
Equalize depths. Let be the ancestor levels up. Jumps compose, so lifting the deeper node by , one jump per 1-bit of , lands on . If that is , then is the answer.
The test. Otherwise at equal depth. Let and the distance from (and from ) up to . Their ancestors at distance coincide exactly when they are at or above :
The descent. So holds exactly when . Scan from down to 0 and jump both nodes whenever the test passes. Initially , and after level the remaining distance satisfies : a jump removes the bit , and no jump means it was already absent. After level 0:
Cost. The table has rows of entries, each computed in ; a query makes at most jumps per phase:
def preprocess(parent, root): # parent[v] for every v != root; nodes 0..n-1
n = len(parent)
children = [[] for _ in range(n)]
for v in range(n):
if v != root:
children[parent[v]].append(v)
depth, order = [0] * n, [root]
for v in order: # BFS order: parents before children
for c in children[v]:
depth[c] = depth[v] + 1
order.append(c)
up = [[root if v == root else parent[v] for v in range(n)]]
for _ in range(max(1, (n - 1).bit_length()) - 1):
prev = up[-1]
up.append([prev[prev[v]] for v in range(n)])
return depth, up
def lca(u, v, depth, up):
if depth[u] < depth[v]:
u, v = v, u
d = depth[u] - depth[v]
for j in range(len(up)): # lift u by d, one bit at a time
if d >> j & 1:
u = up[j][u]
if u == v:
return u
for j in reversed(range(len(up))): # jump while the ancestors still differ
if up[j][u] != up[j][v]:
u, v = up[j][u], up[j][v]
return up[0][u]No recursion, so paths of any length are safe. Checked against the naive method on 400 random trees, including paths and stars. With the LCA, distances follow: , with root distances in place of depths for weighted edges, and the -th node on the path from to is an ancestor of or of , one more lifting query.
Binary lifting on a tree of nodes. How many table entries does the code above store, in millions?
Show the answer
1.7 million
has 17 bits, so there are rows of entries: . That is memory, about 7 MB as 4-byte integers and far more as Python lists, which is one reason to want the -space structures of the next screens.
Euler tours turn LCA into a range minimum
Run a depth-first search from the root and write down a node when it is first entered and again after returning from each of its children. This Euler tour, , has entries, because each of the edges adds one entry going down and one coming back. Record the depth of each entry and the index of each node's first appearance. Consecutive depths differ by exactly .
The range stays inside 's subtree. Let . The search enters before reaching or and leaves for good only after finishing both, so every entry between the two first visits is a node of 's subtree:
The range contains . If , it does at . Otherwise and lie below two different children of , since a single child would be a lower common ancestor; between finishing the first child's subtree and entering the second, the tour writes .
Only is that shallow. Every other node of 's subtree is strictly deeper than , so the minimum depth over the range is attained exactly at the copies of .
tree: A has children B, C; B has D, E; E has G, H; C has F
index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
tour A B D B E G E H E B A C F C A
ℓ 0 1 2 1 2 3 2 3 2 1 0 1 2 1 0
first: A 0 B 1 D 2 E 4 G 5 H 7 C 11 F 12For , scan : the minimum, 1, sits at index 3, where . For , the range reaches 0 at index 10, the root .
A range-minimum structure returns only the minimum value, 1, for , not its position. How can you still name ?
- It is the ancestor of at depth 1, which is
- It is , the entry at index 1 of the tour
- It is any node of depth 1, such as
- You cannot: the position of the minimum is required
Show the answer
A. It is the ancestor of at depth 1, which is
The LCA is an ancestor of , and has exactly one ancestor at each depth. So the minimum value pins it down: the ancestor of at depth 1, here , one level-ancestor query. Structures that return the argmin, such as the sparse table of the next screen, avoid the extra step.
Constant-time queries in linear space
Any range-minimum structure on now answers LCA queries. A sparse table stores, for every start and every power of two , the position of the minimum of , each computed from its two halves. A query takes and compares two windows of length that overlap but together cover the range. The overlap is harmless because the minimum is idempotent: .
def build_sparse(depths):
m = len(depths)
sp = [list(range(m))] # sp[j][i]: argmin of depths[i : i + 2**j]
j = 1
while (1 << j) <= m:
prev, half = sp[-1], 1 << (j - 1)
sp.append([min(prev[i], prev[i + half], key=depths.__getitem__)
for i in range(m - (1 << j) + 1)])
j += 1
return sp
def argmin(sp, depths, l, r): # inclusive range, l <= r
j = (r - l + 1).bit_length() - 1 # largest 2**j <= r - l + 1
a, b = sp[j][l], sp[j][r - (1 << j) + 1] # two windows covering [l, r]
return a if depths[a] <= depths[b] else bWith the tour and the first visits, after ordering the two indices: , the usual contest choice. Checked against the naive method on the same 400 random trees.
Blocks. Cut , of length , into blocks of entries. Keep each block's minimum in an array of entries, and build a sparse table on :
Patterns. Inside a block every step is or , so after subtracting the block's first entry, a block is one of at most patterns, and where the minimum of any sub-range sits depends only on the pattern. Tabulate each pattern that occurs, with all of its sub-ranges:
Queries. A range inside one block is one table lookup. Otherwise it splits into a suffix of 's block, the whole blocks strictly between, and a prefix of 's block: two lookups and one sparse-table query on , then the smallest of three.
In numbers. For : , , at most patterns with entries each, and block minima for the sparse table.
The reduction also runs backward. The Cartesian tree of an array has the position of the minimum at its root and the Cartesian trees of the two sides as its subtrees, and a stack builds it in (the Optimal lesson Cartesian Trees & Nearest Smaller Values). For , the position of the minimum of is the LCA of and in that tree: going down from the root, the first node whose position falls in separates from , and it holds the minimum of its whole subtree (Gabow, Bentley & Tarjan, 1984). Composing the two reductions, RMQ on any array is also .
Offline queries: Tarjan’s algorithm
When all queries are known before the first answer is needed, a single depth-first search answers them all, with a union-find structure and no table at all (Tarjan, 1979). Each node starts as its own set. When a child's subtree is finished, it is merged into its parent's set, and the merged set is anchored at the parent. A query is answered when the search finishes the second of its two nodes.
def offline_lca(children, root, queries): # queries: list of pairs (u, v)
n = len(children)
parent, size, anchor = list(range(n)), [1] * n, list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving
x = parent[x]
return x
asked = [[] for _ in range(n)]
for i, (u, v) in enumerate(queries):
asked[u].append((v, i)); asked[v].append((u, i))
done, ans = [False] * n, [None] * len(queries)
def dfs(u):
for c in children[u]:
dfs(c)
a, b = find(u), find(c) # merge c's finished subtree into u's set
if size[a] < size[b]: a, b = b, a
parent[b], size[a] = a, size[a] + size[b]
anchor[a] = u # the merged set hangs at u, still open
done[u] = True
for v, i in asked[u]:
if done[v]:
ans[i] = anchor[find(v)]
dfs(root)
return ansUnion by size with path halving. The recursion is deep, so on deep trees replace it with an explicit stack. Checked against the naive method on the same 400 random trees, 60 queries each.
Invariant. While the search is at node , the finished nodes and the nodes on the root-to- path are partitioned into sets, one per node on that path, and each set is anchored at its :
It is maintained. When a child of finishes, its whole subtree is finished and forms ; merging it into and anchoring the result at restores the invariant.
The answer. When finishes, take a query with already finished. Then lies in for the deepest node of the root-to- path that is an ancestor of . The ancestors of are exactly that path, so is the deepest common ancestor. Each query is answered once, when the second of its nodes finishes.
The trade-off is the batch: the search answers queries in its own order, so it needs all of them up front. In return it uses memory instead of a table of entries, which makes it the natural choice when the pairs come in one file, as in many offline algorithms.
Lower bounds and the frontier
| Method | Preprocessing | Query | Space | Notes |
|---|---|---|---|---|
| Climb from both nodes | per query on a path | |||
| Binary lifting | words | Also -th ancestors; extends to path minimums and sums | ||
| Euler tour + sparse table | words | The usual contest choice | ||
| Euler tour + blocks | words | Optimal on the RAM; larger constants | ||
| Tarjan's offline algorithm | in total | answered in batch | All queries known in advance |
The answers determine the Cartesian tree. Its root is the position of the minimum of the whole array, and its subtrees are the Cartesian trees of the two sides, found recursively by further queries:
Every shape occurs. List the nodes of any binary tree in inorder and give each the value . The values are distinct and each subtree's root holds its subtree's smallest value, so the Cartesian tree of this array is the tree itself. The Cartesian tree in turn fixes every answer, since an RMQ is an LCA in it, so answer tables and shapes correspond one to one:
Count bits. A structure that never reads the array must tell all these tables apart from its own memory. By Stirling's formula:
For that is about bits, two bits per element. Fischer and Heun (2011) match it up to lower-order terms, with bits and -time queries.
Key takeaways
- Binary lifting stores the -th ancestors: for LCA and -th-ancestor queries, correct because ancestors at distance coincide exactly when reaches the distance to the LCA.
- An Euler tour turns LCA into a range minimum over depths between two first visits; a sparse table gives , and because consecutive depths differ by , blocks of entries have at most patterns, which gives .
- Through Cartesian trees, RMQ and LCA reduce to each other, so both are on the word RAM.
- Offline, Tarjan's depth-first search with union-find answers queries in time and space, in linear time with Gabow and Tarjan's union-find.
- The limits: a pointer machine needs per query, and an index-only RMQ structure needs bits, which Fischer and Heun match up to .
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In the second phase of binary lifting, at equal depth, and both jump by only when . Why not jump when the two ancestors are equal?
- An equal pair may lie strictly above the LCA, so the jump could overshoot it
- Equal ancestors mean that already
- Jumping on equality would raise the query time to
- It would also be correct, but it would need a third phase
Show the answer
A. An equal pair may lie strictly above the LCA, so the jump could overshoot it
Ancestors at distance coincide exactly when , the distance to the LCA. An equal pair says only that : the common node could be the LCA or anything above it. Jumping only while they differ keeps both nodes strictly below the LCA, so the loop ends at two of its children.
Why is the shallowest entry of the Euler tour between and the LCA ?
- The tour lists the nodes in order of increasing depth
- Between those visits the tour stays inside 's subtree and passes through , the only node of its depth there
- The two first visits are at most entries apart
- The root appears between any two first visits
Show the answer
B. Between those visits the tour stays inside 's subtree and passes through , the only node of its depth there
The search cannot leave 's subtree while either or is still unfinished, and it returns to between the two children's subtrees that contain and (or starts at ). Within 's subtree, is strictly the shallowest node.
Which situation calls for Tarjan's offline algorithm rather than a sparse table over the Euler tour?
- Each query must be answered before the next one is read
- Edges are linked and cut between queries
- All queries are given in advance, and memory for a table of entries is short
- The input is a DAG, in which a pair can have several lowest common ancestors
Show the answer
C. All queries are given in advance, and memory for a table of entries is short
The depth-first search answers each query when it finishes the second of its two nodes, so it must know every query up front. In exchange it needs only memory and time, linear with Gabow and Tarjan's union-find.
An RMQ index on distinct numbers answers every query without ever reading the array. Why must it use about bits?
- Each element's value needs 2 bits
- A sparse table needs bits
- The pointer-machine bound forces it
- Its answers determine the array's Cartesian tree, and there are possible shapes
Show the answer
D. Its answers determine the array's Cartesian tree, and there are possible shapes
The answers to all queries fix the Cartesian tree's shape, and every shape occurs, so the index must distinguish cases: bits. Fischer and Heun's structure uses bits, so the bound is tight up to lower-order terms.
Further reading
- D. Harel & R. E. Tarjan, "Fast algorithms for finding nearest common ancestors," SIAM Journal on Computing 13(2) (1984), 338–355.
- B. Schieber & U. Vishkin, "On finding lowest common ancestors: simplification and parallelization," SIAM Journal on Computing (1988).
- R. E. Tarjan, "Applications of path compression on balanced trees," Journal of the ACM 26(4) (1979), 690–715.
- M. A. Bender & M. Farach-Colton, "The LCA problem revisited," LATIN 2000, LNCS 1776 (Springer, 2000), 88–94.
- J. Fischer & V. Heun, "Space-efficient preprocessing schemes for range minimum queries on static arrays," SIAM Journal on Computing (2011).