Skip to content

Lowest Common Ancestor (LCA) ​

The Lowest Common Ancestor (LCA) is an algorithm that finds the first parent vertex where two vertices meet as they move upward in a tree.

At a Glance ​

Think of a family tree. The "closest common ancestor" of you and your cousin is your grandfather. For you and your sibling, it is your parents. The point where two people's ancestral lines first merge like this is the LCA.

→ Finding the first parent vertex where the two vertices meet!

In the figure below, the arrows point from child to parent. Moving up from x and from y, both paths pass through the green vertices (common ancestors), and the lowest of them, the dark green vertex, is the LCA.

A tree where the closest (dark green) of the common ancestors of x and y (light green) is the LCA

Image source: Wikimedia Commons (CC BY-SA 4.0, Qwertyus)

Suppose the tree is given as follows. (1 is the root at the top.)

  • 1
    • 2
      • 4
      • 5
    • 3
      • 6
      • 7
QuestionPath going upLCA
LCA of 4 and 5?4 → 2, 5 → 2The first parent vertex is 2
LCA of 4 and 6?4 → 2 → 1, 6 → 3 → 1The first parent vertex is the root, 1
LCA of 2 and 5?5 → 2 (2 is itself)2

As in the last row, if one vertex is an ancestor of the other, that vertex itself is the LCA. (A vertex is considered its own ancestor.)

How Do We Find It? ​

We store each vertex's depth and parent.

Depth is how many levels below the root a vertex is. The depths of the tree above are as follows.

depthVertices
01 (root vertex)
12, 3
24, 5, 6, 7

Parent is the parent vertex of each vertex. The root has no parent, so we write 0.

Vertex1234567
parent0112233

To look it up directly in code as parent[vertex number], leave slot 0 empty and store it like parent = [0, 0, 1, 1, 2, 2, 3, 3]. depth and parent can be filled in by going down once from the root with BFS or DFS.

How It Works ​

With these two arrays, you can find the LCA of two given vertices a and b. Repeat the following.

  1. If a and b are the same vertex, that vertex is the LCA. (Stop.)
  2. If their depths are equal, move both vertices up one level to their parents.
  3. If their depths are different, move only the deeper vertex up one level to its parent. (Its depth decreases.)

In one line: match the depths → move up together one level at a time → the moment they meet is the LCA.

Example 1) LCA of 4 and 6

Stepabdepth(a), depth(b)What happened
Start462, 2Same depth, different vertices → both move to their parents
1231, 1Same depth, different vertices → both move to their parents
2110, 0Same vertex → LCA = 1

Example 2) LCA of 5 and 2

Stepabdepth(a), depth(b)What happened
Start522, 15 is deeper → only 5 moves to its parent
1221, 1Same vertex → LCA = 2

In Example 2, if you only compared "whether the two vertices' parents are the same," you would make the mistake of answering 1, the parent of 2 and 2. That is why you must first check whether the vertices themselves are the same.

Python Code ​

python
from collections import deque


def build_tree(n, edges, root=1):
    # 1. Build the connection info (adjacency list)
    graph = [[] for _ in range(n + 1)]
    for a, b in edges:
        graph[a].append(b)
        graph[b].append(a)

    # 2. Go down from the root with BFS and fill in depth and parent
    depth = [0] * (n + 1)
    parent = [0] * (n + 1)           # The root has no parent, so 0
    visited = [False] * (n + 1)
    visited[root] = True
    queue = deque([root])
    while queue:
        cur = queue.popleft()
        for nxt in graph[cur]:
            if not visited[nxt]:
                visited[nxt] = True
                depth[nxt] = depth[cur] + 1
                parent[nxt] = cur
                queue.append(nxt)
    return depth, parent


def lca(a, b, depth, parent):
    while True:
        # 3. Once they are the same vertex, that vertex is the LCA
        if a == b:
            return a
        # 4. If depths are equal, move both up one level
        if depth[a] == depth[b]:
            a, b = parent[a], parent[b]
        # 5. If depths differ, move only the deeper one up one level
        elif depth[a] > depth[b]:
            a = parent[a]
        else:
            b = parent[b]


edges = [(1, 2), (1, 3), (2, 4), (2, 5), (3, 6), (3, 7)]
depth, parent = build_tree(7, edges)
print(depth[1:])                 # Output: [0, 1, 1, 2, 2, 2, 2]
print(parent[1:])                # Output: [0, 1, 1, 2, 2, 3, 3]
print(lca(4, 5, depth, parent))  # Output: 2
print(lca(4, 6, depth, parent))  # Output: 1
print(lca(2, 4, depth, parent))  # Output: 2
  1. Convert the edge list into "a list of neighbors for each vertex." Tree edges have no direction, so add them on both sides.
  2. Going down from the root with BFS, record each newly found neighbor's depth as "my depth + 1" and its parent as "me."
  3. When the two vertices become the same, that is the first meeting point, i.e. the LCA. Doing this check first ensures the case where one vertex is an ancestor of the other is handled correctly.
  4. If the depths are equal but the vertices differ, they have not met yet, so both move up one level.
  5. If the depths differ, move only the deeper one up to match the heights first.

Faster: Jumping by Powers of 2 ​

The method above moves up one level at a time, so if the tree is stretched out in a long line, a single query can move up as many as N times. When there are many queries, we precompute a table of "the ancestor 2 levels up, 4 levels up, 8 levels up" and make big jumps (sparse table, Binary Lifting). This is supplementary content not in the original source.

python
def build_table(n, parent):
    # 1. LOG = the smallest exponent such that 2^LOG >= n
    LOG = max(1, n.bit_length())
    # 2. up[k][v] = ancestor 2^k levels above v (0 if none)
    up = [parent[:]]
    for k in range(1, LOG):
        prev = up[k - 1]
        up.append([prev[prev[v]] for v in range(n + 1)])
    return up


def lca_fast(a, b, depth, up):
    # 3. Make a the deeper one
    if depth[a] < depth[b]:
        a, b = b, a
    # 4. Break the depth difference into binary and jump at once
    diff = depth[a] - depth[b]
    k = 0
    while diff:
        if diff & 1:
            a = up[k][a]
        diff >>= 1
        k += 1
    if a == b:
        return a
    # 5. Move up together, starting with big jumps, while the ancestors differ
    for k in range(len(up) - 1, -1, -1):
        if up[k][a] != up[k][b]:
            a, b = up[k][a], up[k][b]
    return up[0][a]


depth = [0, 0, 1, 1, 2, 2, 2, 2]
parent = [0, 0, 1, 1, 2, 2, 3, 3]
up = build_table(7, parent)
print(lca_fast(4, 5, depth, up))  # Output: 2
print(lca_fast(4, 6, depth, up))  # Output: 1
print(lca_fast(7, 3, depth, up))  # Output: 3
  1. Depth is less than N, so it is enough to prepare power-of-2 jumps for as many bits as N has.
  2. The table is filled using the property "2^k levels up" = "2^(k-1) levels up from the point 2^(k-1) levels up." Above the root is 0, and the parent of 0 is also 0, so nothing goes outside the table.
  3. Swap positions so that a is always the deeper one.
  4. If the depth difference is 5 (binary 101), the heights are matched with two jumps: 1 level and 4 levels.
  5. Try the big jumps first, and only actually move up when the landing spots differ. At the end, the two vertices sit right below the LCA, so the answer is one level up.

Time and Space Complexity ​

N is the number of vertices and h is the height of the tree.

MethodPreparation (preprocessing)One query: bestOne query: averageOne query: worstSpace
Moving up one level at a timeO(N)O(1)O(h)O(N)O(N)
Power-of-2 jumpsO(N log N)O(1)O(log N)O(log N)O(N log N)
  • With the one-level-at-a-time method, the number of moves is up to the height of the tree. If the tree stretches into a single line, the height becomes N, so the worst case is O(N).
  • The jump method spends more time and memory building the table, but each query jumps only log N times. If time complexity notation is unfamiliar, read the time complexity article first.

Where It Is Used ​

Use it in tree problems where you need to find a common ancestor, or where you need the travel distance or the path between two vertices.

  • Distance between two vertices: depth[a] + depth[b] - 2 * depth[LCA]. Example) 4 and 6 are 2 + 2 - 2 × 0 = 4 steps apart (4 → 2 → 1 → 3 → 6).
  • Path between two vertices: the path going up from a to the LCA + the path going down from the LCA to b.

Git's merge-base ​

When Git merges two branches, it first finds the common commit right before the two branches diverged (the merge-base). Only by comparing against that point can it tell "what each side changed." This is exactly the LCA.

However, the commit graph is a DAG where a commit can have multiple parents, so it is a bit more complex than a tree. Still, the idea of "the place where both ancestral lines first meet" is the same. You can see the commit and parent structure in Mini Git Structure.

Summary ​

ConceptPlain-language summary
LCAThe first shared ancestor found by tracing two people's family trees upward
depth / parentNotes on "how many levels below the root" and "who the parent right above is"
Basic methodMatch the depths, then move up together one level at a time; where they meet is the answer
Jump methodWrite down the ancestors 2, 4 and 8 levels up in advance and leap upward in big steps
merge-baseThe common commit right before two Git branches diverged