← Lessons

quiz vs the machine

Gold1470

Algorithms

Lowest Common Ancestor with Binary Lifting

Jump up a tree in powers of two to find shared ancestors fast.

5 min read · core · beat Gold to climb

The lowest common ancestor

The lowest common ancestor of two nodes is the deepest node that is an ancestor of both. Walking up one step at a time is slow on deep trees, so we precompute jumps of growing size.

Binary lifting

Precompute, for every node, its ancestor that is one step up, two steps up, four steps up, and so on in powers of two. Each such ancestor is found by combining two smaller jumps that are already known. This sparse table is built once over the whole tree.

Answering a query

To find the ancestor shared by two nodes:

  • First lift the deeper node up until both nodes sit at the same depth.
  • Then lift both nodes together by the largest jumps that keep them apart.
  • When no jump moves them apart, their parent is the answer.

Because depths and gaps are written in binary, a handful of power of two jumps cover any distance. Each query resolves in time that grows only with the logarithm of the tree height.

Key idea

Store each node's ancestors at power of two distances so two nodes can be raised to a shared ancestor with a few binary jumps.

Check yourself

Answer to earn rating on the learn ladder.

1. What does binary lifting precompute for each node?

2. What is the first step when answering a query?