learngraphtheory.org

Guest

Sign in to keep your graphs and progress.

Cover of the book Graph Theory Through Problems

Practice book

Graph Theory Through Problems

300 Exercises with Hints, Worked Algorithms and Complete Solutions

By Mohammed Islam Hadjoudj

Learn graph theory by solving problems: 300 exercises, from routine checks to challenging proofs, each with a complete solution.

Available inKindlePaperback

13 chapters

Also by the authorGraph Algorithms for Coding Interviews100 solved interview problems with visual explanations and Python solutions.View on Amazon
Algorithm Selection

Select an algorithm and generate steps to begin visualization

Lowest Common Ancestor

Where two branches of a tree meet

Prepares a table of 2^k-th ancestors, then finds the first vertex u and v share on the way to the root in O(log n) jumps

Time: O(n log n) + O(log n) per query
Space: O(n log n)
Use Case: Distances in trees, version control, phylogenetic trees, coding interviews
Showing the example graph for this algorithm.
Algorithm Execution

Select an algorithm and generate steps to begin visualization

About Lowest Common Ancestor (Binary Lifting)

In a rooted tree, the lowest common ancestor (LCA) of two vertices u and v is the deepest vertex that lies on both of their paths up to the root: the point where their branches meet. Together, the two paths from u and v up to the LCA form the unique path between u and v in the tree, which is why LCA queries answer distance questions on trees. It is one of the most common tree problems in coding interviews and competitive programming.

How it works

Binary lifting prepares a table once. A BFS from the root gives every vertex its depth and parent: row 0. Row k holds each vertex's 2^k-th ancestor, built from the row before: two jumps of 2^(k−1). A query first lifts the deeper vertex to the other's depth, one power of two for each 1 bit of the depth difference. If both are now the same vertex, that is the answer. Otherwise both jump together from the largest power down, but only when their ancestors differ, so they never jump past the meeting point. They end just below it, and the LCA is their parent. Preparation takes O(n log n), each query O(log n). The visualizer draws the parent pointers, the jumps of each row and every lift of the query.

Applications

Distances in trees: dist(u, v) = depth(u) + depth(v) − 2·depth(LCA). Version control finds the merge base of two branches (a common ancestor in the commit graph), biology finds the most recent common ancestor of two species in a phylogenetic tree, and networks with tree topology route messages through it. Binary lifting itself is a general trick: precomputed jumps of powers of two answer "k steps up" or "k steps later" queries in logarithmic time.

Pseudocode

Preparation builds the table once. Each query then lifts and jumps through it.

Prepare(tree, root):
    depth, parent = BFS from root  // parent(root) = root
    up[0][x] = parent(x) for every vertex x
    for k = 1 to LOG - 1:
        up[k][x] = up[k-1][ up[k-1][x] ]

LCA(u, v):
    if depth[u] < depth[v]: swap u and v
    for each bit k set in depth[u] - depth[v]:
        u = up[k][u]
    if u == v: return u
    for k = LOG - 1 down to 0:
        if up[k][u] != up[k][v]:
            u = up[k][u]
            v = up[k][v]
    return up[0][u]

LOG is the number of bits needed for the largest depth. Making the root its own parent means up[k][x] is always defined: jumping too far simply lands on the root.

Worked example, step by step

The query loaded on this page: the lowest common ancestor of L and J.

Example graph: A twelve-vertex tree rooted at A (the top vertex). B and C are A's children, D and E are B's, H is D's, L is H's, and I and J are E's.

  1. Depths. A BFS from A gives depths: L is at depth 4, J at depth 3. Row 0 of the table holds each parent.
  2. The table. Row 1 holds ancestors 2 levels up, row 2 ancestors 4 levels up. For L: H, then D (two up), then A (four up).
  3. Same depth. The depth difference is 1 (binary 1), so L is lifted once by 1, to H. H and J are both at depth 3.
  4. Jumps that are skipped. Jumping 4 would put both on A, jumping 2 both on B: a common vertex, possibly too high, so both jumps are skipped.
  5. The safe jump. Jumping 1 leads to D and E, which differ, so both jump. Their parent, B, is the answer.

The lowest common ancestor of L and J is B. The path between L and J in the tree goes 3 edges up from L and 2 up from J, meeting at B.

Complexity, and where it comes from

Time: O(n log n) preparation, O(log n) per query · Space: O(n log n)

The table has about log₂ n rows of n entries, and each entry is filled in O(1) from the row before. A query makes at most log n lifts to equalise depths and at most log n jump decisions, each O(1). For q queries the total is O((n + q) log n).

When to use Lowest Common Ancestor (Binary Lifting), and when not to

Several LCA methods trade preparation time against query time.

AlternativePrefer it whenCost
Walk up step by stepOne query on a shallow tree. No preparation.O(depth) per query
Euler tour + sparse table (RMQ)Many queries: O(1) each after O(n log n) preparation.O(n log n) + O(1)
Tarjan's offline LCAAll queries known in advance: one DFS with union-find answers them all.O((n + q)·α(n))

Common pitfalls

  • Jumping when the ancestors are equal. Equal ancestors are common ancestors, but maybe not the lowest one. Jump only when they differ, and take the parent at the end.
  • Forgetting to equalise depths. The joint jumps assume both vertices are at the same depth. Without the first lifting step they skip past the answer.
  • Too few rows. The table needs enough rows for the largest depth. With one row too few, a deep vertex cannot be lifted far enough and the query goes wrong.

Frequently asked questions

What is the lowest common ancestor?
In a rooted tree, the deepest vertex that is an ancestor of both u and v. A vertex counts as its own ancestor, so the LCA of u and one of u's descendants is u itself.
Why does binary lifting work?
Every number of steps up can be written as a sum of powers of two, and the table holds a jump for each power, so any ancestor is at most log n jumps away.
How do I get the distance between two tree vertices?
dist(u, v) = depth(u) + depth(v) − 2 · depth(LCA(u, v)): up from u to the LCA, then down to v.
Does the choice of root matter?
Yes, the LCA depends on the root. The path between two vertices does not, which is why distances come out the same whatever the root.

Related algorithms: Tree Traversal (Pre, In, Post, Level), Breadth-First Search, Depth-First Search, Union-Find (Disjoint Set Union), Prüfer Code

An example graph: you can change it, or start blank.

Zoom Controls

30%
Nodes: 12
Edges: 11