Binary Lifting
Binary lifting (AKA binary jumping) is a very cool algorithm for finding the lowest common ancestor (LCA) of two nodes in a tree. I like it because it changed the way I look at other algorithms, for instance binary search and sparse tables, and visualizing this algorithm gave me a much deeper understanding of it. It is also quite efficient: queries only take \( O(\log(n)) \) time, where \( n \) is the size of the tree.
To accomplish this time, it is inevitable that we have to preprocess the tree beforehand. This preprocessing takes \( O(n \cdot \log(n)) \) time and space, so only slightly worse than reading in the tree to begin with.
The Lowest Common Ancestor
If we have a tree \( T \) and a node \( u \), then the ancestors of \( u \) are \( u \) itself, its parent, its parent's parent, etc. If we have two nodes \( u \) and \( v \), then their common ancestors are just the nodes that are ancestors of both; the lowest common ancestor, written as \( \mathit{LCA}(u, v) \), is the one with the highest depth.
A sample tree.
The ancestors of \( u \).
The ancestors of \( v \).
The LCA of \( u \) and \( v \).
Fact: the path between \( u \) and \( v \) is always the path that goes from \( u \) to \( \mathit{LCA}(u, v) \) concatenated with the path from \( \mathit{LCA}(u, v) \) to \( v \).
So, if you have a tree and you want to efficiently query the shortest path between any two nodes, you can reduce the problem to querying the LCA. You can also extend this technique to make path queries, for instance finding the length of the path between two nodes. Finally, it's an important algorithm to know for competitive programming.
A Naive Attempt
When approaching any algorithmic problem, it's good practice to first think of the most obvious, inefficient solution and see what it reveals about the problem. Also, often it's possible we notice it does some unnecessary work, and we can use some kind of data structure or trick to avoid that work and to get an efficient solution.
Before reading on, try to think of a "dumb" algorithm that solves the problem just by walking around the tree.
We can imagine two naive solutions. One is a top-down algorithm that starts at the root and traverses the tree until it finds \( u \) and \( v \):
The marked node is the lowest that has both \( u \) and \( v \) as children.
We have to traverse the whole tree since we don't know where \( u \) and \( v \) are if we start from the root, so this approach is \( O(n) \).
Another solution is a bottom-up algorithm that starts at \( u \) and \( v \) and goes up until it finds a common ancestor:
We climb up from \( v \), each time checking if the found node is also an ancestor of \( u \).
\( v \) itself is not an ancestor of \( u \).
Not an ancestor of \( u \).
The marked node is the first ancestor of \( v \) that is also ancestor of \( u \).
This algorithm is \( O(d_u \cdot d_v) \) where \( d \) denotes the depth of a node. If we don't know the tree is balanced, the depth of a node is \( O(n) \), so this algorithm is worst case \( O(n^2) \) which is very bad. There are two easy ways to avoid having to visit all ancestors of \( u \) for each ancestor of \( v \); try to think how you would do this!
One easy way to speed it up easily by only going up from \( u \) once, marking all the ancestors, so when we go up from \( v \) we know we've found the LCA when the node is marked. This is \( O(d_u + d_v) \), so worst case \( O(n) \) per query.
Another trick we can do is to first move up from the deeper node to the depth of the shallower node. Then we can climb up from both in parallel, until the two paths meet:
First, move up to the same depth.
Now we can move up in parallel.
The marked node is the first ancestor of both.
This is also \( O(d_u + d_v) = O(n) \), but we do have to preprocess by labeling each node with its depth. This takes \( O(n) \) preprocessing time and \( O(n) \) extra space.
If we take a look at the node pairs that we visit with this parallel climb, we get the following sequence:
\( (6, 11), (5, 10), (3, 9), (2, 2), (1, 1) \)
The LCA is 2, so the first node where the pair of nodes visited by the parallel climb is equal.
Observation: for every two nodes at the same depth, such a sequence of ancestor is in a sense monotonic w.r.t. them being common ancestors. In other words, once the pair of ancestors are equal, any subsequent pair will also be equal.
The idea behind binary lifting is that we don't have to do a linear search; by exploiting this observation, we can actually do a binary search. Since we can't easily split the path from root to \( u \) and \( v \) down the middle like in normal binary search, we can use a variant of binary search called Shar's algorithm.
Shar's algorithm
Normal binary search tries to find the first position \( i \) in a sequence where some condition \( f \) holds. It splits a sequence down the middle, then narrows down the search to either the left half or the right half, and proceeds recursively. This works if the sequence is sorted, in other words, if \( f \) is monotonic for the sequence: if \( f \) holds at position \( i \), then it also holds at every position \( j > i \).
Our binary search instead finds the last position before \( f \) becomes true; finding the first position where \( f \) does hold is then trivial, it is just the next one. Shar's algorithm start at element 0 and tries to make steps of \( 2^k, 2^{k - 1}, \dots, 2^0 \) where \( k = \lfloor \log_2(n) \rfloor \). It only makes the jumps if the step does not overshoot into a position where \( f \) is true.
Example: in this monotonic sequence, we're looking for the first element \( \geq 7 \). We do this by finding the last element \( \lt 7 \).
Start at first element.
Try jump of \( 2^3 = 8 \): overshoots.
Make jump of \( 2^2 = 4 \): still in red zone.
Make jump of \( 2^1 = 2 \): overshoots.
Make jump of \( 2^0 = 1 \): still in red zone.
Done! The last red element is 6, so the first green element is 7.
This algorithm fails when the whole sequence passes the condition (everything is green), but that is an edge case we can easily handle by checking the first element at the start.
This implementation of Shar's algorithm uses a few more checks than strictly necessary, but still only \( O(\log(n)) \), so it will work for our LCA purposes. If you want a more in-depth explanation of Shar's algorithm and how to make it optimal, I think orlp.net has a very good one.
Shar's Algorithm in a Tree
Binary lifting is the application of this principle to a tree. We just need to do some preprocessing to allow us to make these power-of-2 jumps upwards from any node. Since the depth \( d \) of any node is less than \( n \), and every node has at most \( O(\log(d)) \) powers-of-2 jumps, the total time and space of this preprocessing is \( O(n \cdot \log(n)) \).
Preprocessing: start DFS at root
Upward jump of 1.
Upward jumps of 1, 2.
Upward jumps of 1, 2, 4.
Upward jumps of 1, 2.
Upward jumps of 1, 2, 4.
Upward jump of 1.
The LCA algorithm first has to get both nodes up to the same depth so we can do our parallel climb. To reformulate it as a search problem: find the highest-depth ancestor of \( v \) such that its depth is not strictly smaller than \( u \). We use the idea of Shar's method to make as large as possible power-of-2 jumps from the deeper node upwards to the depth of the other node.
Our preprocessing gives us jumps of 1, 2, and 4.
Try jump of \( 2^2 = 4 \): overshoots.
Try jump of \( 2^1 = 2 \): overshoots.
Try jump of \( 2^0 = 1 \): not too far!
Start next phase from nodes 6 and 11.
An alternative way to understand this: take the binary representation of the depth difference and take the steps corresponding to the 1 bits. For instance, if we have nodes at depth 2 and 15, then the difference is 13 = 0b1101, so we want to take steps of \( 2^3 \), \( 2^2 \), and \( 2^0 \), since \( 2^3 + 2^2 + 2^0 = 13 \).
Now we can start the second phase, where we just use the principles of Shar's algorithm again! Keep making the largest power-of-2 step you can without overshooting, and then you're just done.
Because of our preprocessing, we can make jumps of 1, 2, or 4.
Try jump of \( 2^2 = 4 \): overshoots.
Try jump of \( 2^1 = 2 \): not too far, move there.
Try jump of \( 2^0 = 1 \): overshoots.
We found the most shallow nodes that are not common ancestors of \( u \) and \( v \).
The deepest node that is a common ancestor, the LCA, is their direct parent.
In the implementation, we should keep in mind the edge case where the nodes are already equal after the first phase.
Implementation
The full code is available on this website. I've tested it on judge.yosupo.jp. All code is licensed under GPL3 (see the COPYING file). It needs C++20 because of bit_width.
Some implementations simplify the code by adding a constant number \( k = \lceil \log_2(n) \rceil \) of upward jumps to every node, even if they do not actually have those jumps, and having the non-existent jumps point to the root. This uses a bit of extra memory in practice but does not worsen the complexity. It also has the downside that it does not allow for the efficient insertion of new leaf nodes later on while preserving this property, since that would increase \( n \).
First we have scaffolding code and some preprocessing. The trick we use to initialize the power-of-2 jumps of each node is to add up jumps we've added before. For instance, a jump of \( 2^4 \) is just two jumps of \( 2^3 \).
// Copyright 2026 emilia-h
#include <bit>
#include <cassert>
#include <iostream>
#include <vector>
struct Node {
int depth = 0;
std::vector<int> children;
std::vector<int> jumps;
};
using Tree = std::vector<Node>;
void initJumps(Tree& tree, int u, int parent) {
if (parent != -1) {
tree[u].depth = tree[parent].depth + 1;
tree[u].jumps.push_back(parent);
}
for (int i = 1; i < std::bit_width((unsigned) tree[u].depth); i++) {
// jump of 2^i = jump of 2^(i - 1) + jump of 2^(i - 1)
tree[u].jumps.push_back(tree[tree[u].jumps[i - 1]].jumps[i - 1]);
}
for (int v : tree[u].children) {
initJumps(tree, v, u);
}
}
Now we have the LCA algorithm. As described before, first we get the nodes up to the same depth. One trick you can do is to swap \( u \) and \( v \) if the depth of \( u \) is smaller, so \( u \) is always the node to lift up to the depth of \( v \), which is allowed because the LCA is symmetric.
After that, we perform the parallel climb, keeping in mind the edge case where \( u \) and \( v \) are already equal.
int lca(const Tree& tree, int u, int v) {
if (tree[u].depth < tree[v].depth) {
std::swap(u, v);
}
// get u to same depth as v
for (int bit = std::bit_width((unsigned) tree[u].depth) - 1; bit >= 0; bit--) {
if (bit >= tree[u].jumps.size()) {
continue;
}
int u2 = tree[u].jumps[bit];
if (tree[u2].depth >= tree[v].depth) {
u = u2;
}
}
assert(tree[u].depth == tree[v].depth);
if (u == v) {
return u;
}
// parallel climb to find lca
for (int bit = std::bit_width((unsigned) tree[u].depth) - 1; bit >= 0; bit--) {
if (bit >= tree[u].jumps.size()) continue;
int u2 = tree[u].jumps[bit];
int v2 = tree[v].jumps[bit];
if (u2 != v2) {
u = u2;
v = v2;
}
}
return tree[u].jumps[0];
}
Finally, we have some boilerplate to read in the graph, so I can test it. The format is described on judge.yosupo.jp.
int main() {
int n, q;
std::cin >> n >> q;
Tree tree(n);
for (int i = 1; i < n; i++) {
int p;
std::cin >> p;
tree[p].children.push_back(i);
}
initJumps(tree, 0, -1);
for (int i = 0; i < q; i++) {
int u, v;
std::cin >> u >> v;
std::cout << lca(tree, u, v) << "\n";
}
return 0;
}
The input format is as follows. On the first line, there are two integers \( n \) and \( q \), which are the number of nodes and the number of queries, respectively. Then on the next line, there are \( n - 1 \) integers \( p_1, ..., p_{n - 1} \) which are the parents of the nodes (0-indexed), not including node 0 which is the root. Then there are \( q \) lines of queries, each containing two integers \( u \) and \( v \) which are the node pairs that we want to find the LCA of.
Extensions
Dynamic variant: this algorithm can easily be extended to the dynamic version of the problem. In the dynamic version, instead of getting the whole tree in one go and then preprocessing, instead we just start with a root and get "leaf insertion" queries, which add a new child node somewhere while keeping the upward jumps up-to-date and can take \( O(\log(n)) \) time, in addition to normal LCA queries. This problem is more difficult than the static variant, but our algorithm is barely any more difficult since the upward jumps from a node can be easily computed from the upward jumps of its ancestors.
Range queries: a sparse table is a data structure, which given an array \( A \) and a binary operation \( \circ \), allows you to efficiently query \( A[i] \circ A[i + 1] \circ \dots \circ A[j] \). This works for any associative and commutative operation, like addition, multiplication, minimum and maximum. This data structure uses the same principles: at every index, store precomputed values of range queries forward from that index, for powers of 2:
- \( A[i] \circ A[i + 1] \)
- \( A[i] \circ \dots \circ A[i + 2] \)
- \( A[i] \circ \dots \circ A[i + 4] \)
- \( A[i] \circ \dots \circ A[i + 8] \)
You can then compute it for any range \( [i, j] \) by taking the binary representation of \( j - i \) and accumulating the precomputed values for only the 1 bits, just like we did with binary lifting.
We can extend the sparse table for trees as well, allowing us to do path range queries between two nodes \( u \) and \( v \). Take for instance addition. Apart from storing for every \( k \) the jump from \( u \) to its \( 2^k \)th ancestor, we also store precomputed sums along that upward jump:
Each edge is associated with a weight.
Example: for \( u \), store in the upward jumps: \( 6 \), \( 6 + 2 \), \( 6 + 2 + 10 + 1 \).
Since the path between two nodes \( u \) and \( v \) always goes up from \( u \) to \( \mathit{LCA}(u, v) \) and then back down to \( v \), we can answer path queries in trees by computing the range queries along those two sub-paths and then adding them together.
Apply the same algorithm, just add the values of the jumps along the way: \( 8 + 10 + 11 + 1 + 7 \).
Dynamic range query variant: This algorithm works just as well for the dynamic variant where you can add a new leaf node along with a weighted edge to it. However, if you want a dynamic variant where you can modify existing edge weights, things become trickier, since one edge weight can change the values associated with many upward jumps. For this you need Heavy-Light Decomposition, where you partition the nodes into \( O(\log(n)) \) paths each of \( O(n) \) size, and maintain efficient range queries by associating each path with a segment tree.
If you want it all, so creating new nodes, the creating or deleting new edges between several trees, and updating the values on them, you will have to resort to the Link-Cut Tree, an extremely complex data structure.
Even better algorithm: there is even an \( O(1) \) algorithm which works by reducing the problem to Range Minimum Queries using the Euler tour representation of the tree, with only \( O(n) \) preprocessing. It is outside the scope of this already way too long article, but there's a nice SithDev youtube video, which coincidentally came out a little bit after I started making this article.
Finally, keep in mind that the binary lifting algorithm can also be used to simply find the \( i \)th ancestor of a node, by converting \( i \) to its binary representation and taking a jump for every 1 bit. The reason I approach it from an LCA angle is because it is a fun problem that has many uses in other algorithms :)
Copyright emilia-h 2025-2026 licensed under CC BY-SA 4.0