AlgoTales · Roadmap

Binary lifting

Advanced · 11 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Binary lifting stores, for every node in a tree, where you land after jumping 1, 2, 4, 8 and so on steps upward. Any long climb is then made of only a few jumps. It is a handy way to ask "who is the ancestor N levels up?" quickly.

Practical use cases

  • Web app: Nearest common manager in an org chart. An HR portal with 50,000 employees must show the closest manager that two people share. Walking up one level at a time from each is slow. With stored jumps, both climb to the same depth in a few hops and then climb together, finding the manager almost instantly.
  • Web app: Nested comment threads. A forum with deeply nested replies needs the common parent of two comments to show "in reply to the same thread". Stored jumps find the shared ancestor without climbing the entire thread. The forum can show the shared parent right away, even in a thread that has gone 200 replies deep.
  • Web app: Category tree breadcrumbs. A shop with categories nested 30 levels deep asks "what is this product's ancestor 25 levels up?" for filters. Three precomputed jumps (16, then 8, then 1 level) answer it without walking up the tree one level at a time, so the filter stays quick even on a very tall category tree.
  • System: Version history and dependency chains. Version-control history and package chains are trees too. Skip pointers let tools find a shared earlier version without stepping through every version in between, so the answer comes back in a few jumps.

The story: Grandpa Bhaskar's Family Ladder

At the family reunion, Grandpa Bhaskar loved quizzing the kids: "Mira, who is your great-great-grandfather?" That meant walking up the family tree five steps: father, grandfather, great-grandfather, and so on. Fine for five steps.

But Aarav had built a family tree app for a village with a million ancestors in a chain, and users kept asking "who is the 700,000th ancestor?" Walking step by step took ages per question.

Mira found a shortcut. "Let each person remember a few special ancestors: 1 step up, 2 steps, 4 steps, 8 steps, 16... up. To climb 13 steps, use 8 + 4 + 1. Three jumps and we are there."

Every number can be built from powers of two, just like any amount of money from coins of 1, 2, 4 and 8. This clever table of power-of-two jumps is called binary lifting. It turns a long climb into just a few hops.

How to spot this problem, and where you need it

You repeatedly climb a tree or chain upward, step by step, to find an ancestor or a common parent, and the climb gets long on deep structures.

Signs you need it

  • Your code uses a while loop on parent_id again and again for many queries.
  • The questions are "k-th ancestor", "lowest common ancestor" or "first ancestor satisfying something".
  • The tree has long chains, so walking up is fast for shallow data but slow for deep data.

Where to use it in a project

  • Org-chart and reporting-line lookups such as the nearest shared manager of two people.
  • Nested comments, folders and category trees where many ancestor questions are asked.
  • Finding the shared base version in a version history of changes.

The solution

For each node, precompute its parent, the node 2 steps up, 4 steps up, 8 steps up and so on by combining the previous jumps (two jumps of 4 make one of 8). To climb k steps, break k into powers of two (13 is 8 plus 4 plus 1) and take those jumps. For a common ancestor, first lift the deeper node to the same depth, then lift both together with the biggest jumps that keep them apart, and finish with one step.

Payoff: Before: up to 1,000 steps per question on a deep tree. After: about 10 jumps.

Explain it like I am 8

Imagine a staircase with 1,000 steps. You have a magic pair of shoes that can jump 1, 2, 4, 8, 16... steps. To go up 13 steps, you do one jump of 8, one of 4, and one of 1. Only three jumps instead of thirteen.

How it works, step by step

  1. Row 0: store each node's parent (the 1-step jump). Use 0 for "no parent".
  2. Row j: the 2j-step ancestor equals the 2j-1-step ancestor of the 2j-1-step ancestor. up[j][v] = up[j-1][ up[j-1][v] ].
  3. To climb k steps, look at the binary digits of k (5 is 101: a 1-jump and a 4-jump).
  4. For every digit that is 1, jump with that row: v = up[j][v].
  5. If you ever land on "none", the ancestor does not exist. The same table can find the lowest common ancestor of two nodes.

The code in four languages

PHP

<?php
// Binary lifting: answer "who is the k-th ancestor of v?" fast.
const LOG = 3;                                   // enough for jumps up to 7 steps

// parent[v] = the node one step above v (0 means "no parent", node 0 is not used)
$parent = [0, 0, 1, 1, 2, 2, 4, 6, 7];           // nodes 1..8
$n = count($parent) - 1;

// up[j][v] = the node 2^j steps above v (0 if it does not exist)
$up = [$parent];
for ($j = 1; $j < LOG; $j++) {
    $row = [];
    for ($v = 0; $v <= $n; $v++) {
        $row[$v] = $up[$j - 1][$up[$j - 1][$v]]; // jump half, then jump half again
    }
    $up[] = $row;
}

function kthAncestor(array $up, int $v, int $k): int {
    for ($j = 0; $j < LOG; $j++) {
        if ($k >> $j & 1) $v = $up[$j][$v];      // this binary digit is 1: use that jump
    }
    return $v;                                   // 0 means "no such ancestor"
}

echo kthAncestor($up, 8, 5), "\n";               // 1
echo kthAncestor($up, 6, 2), "\n";               // 2
echo kthAncestor($up, 8, 7), "\n";               // 0 (we fell off the top)

JavaScript

// Binary lifting: answer "who is the k-th ancestor of v?" fast.
const LOG = 3;                                   // enough for jumps up to 7 steps

// parent[v] = the node one step above v (0 means "no parent", node 0 is not used)
const parent = [0, 0, 1, 1, 2, 2, 4, 6, 7];      // nodes 1..8
const n = parent.length - 1;

// up[j][v] = the node 2^j steps above v (0 if it does not exist)
const up = [parent];
for (let j = 1; j < LOG; j++) {
  const row = [];
  for (let v = 0; v <= n; v++) {
    row[v] = up[j - 1][up[j - 1][v]];            // jump half, then jump half again
  }
  up.push(row);
}

function kthAncestor(v, k) {
  for (let j = 0; j < LOG; j++) {
    if (k >> j & 1) v = up[j][v];                // this binary digit is 1: use that jump
  }
  return v;                                      // 0 means "no such ancestor"
}

console.log(kthAncestor(8, 5));                  // 1
console.log(kthAncestor(6, 2));                  // 2
console.log(kthAncestor(8, 7));                  // 0 (we fell off the top)

Java

public class Main {
    static final int LOG = 3;                        // enough for jumps up to 7 steps

    // Who is the k-th ancestor of v? 0 means "no such ancestor".
    static int kthAncestor(int[][] up, int v, int k) {
        for (int j = 0; j < LOG; j++) {
            if ((k >> j & 1) == 1) v = up[j][v];     // this binary digit is 1: use that jump
        }
        return v;                                    // 0 means "no such ancestor"
    }

    public static void main(String[] args) {
        // parent[v] = the node one step above v (0 means "no parent", node 0 is not used)
        int[] parent = {0, 0, 1, 1, 2, 2, 4, 6, 7};  // nodes 1..8
        int n = parent.length - 1;

        // up[j][v] = the node 2^j steps above v (0 if it does not exist)
        int[][] up = new int[LOG][n + 1];
        up[0] = parent;
        for (int j = 1; j < LOG; j++) {
            for (int v = 0; v <= n; v++) {
                up[j][v] = up[j - 1][up[j - 1][v]];  // jump half, then jump half again
            }
        }

        System.out.println(kthAncestor(up, 8, 5));   // 1
        System.out.println(kthAncestor(up, 6, 2));   // 2
        System.out.println(kthAncestor(up, 8, 7));   // 0 (we fell off the top)
    }
}

Go

package main

import "fmt"

const LOG = 3 // enough for jumps up to 7 steps

// kthAncestor finds the k-th ancestor of v. 0 means "no such ancestor".
func kthAncestor(up [][]int, v, k int) int {
	for j := 0; j < LOG; j++ {
		if k>>j&1 == 1 {
			v = up[j][v] // this binary digit is 1: use that jump
		}
	}
	return v // 0 means "no such ancestor"
}

func main() {
	// parent[v] = the node one step above v (0 means "no parent", node 0 is not used)
	parent := []int{0, 0, 1, 1, 2, 2, 4, 6, 7} // nodes 1..8
	n := len(parent) - 1

	// up[j][v] = the node 2^j steps above v (0 if it does not exist)
	up := [][]int{parent}
	for j := 1; j < LOG; j++ {
		row := make([]int, n+1)
		for v := 0; v <= n; v++ {
			row[v] = up[j-1][up[j-1][v]] // jump half, then jump half again
		}
		up = append(up, row)
	}

	fmt.Println(kthAncestor(up, 8, 5)) // 1
	fmt.Println(kthAncestor(up, 6, 2)) // 2
	fmt.Println(kthAncestor(up, 8, 7)) // 0 (we fell off the top)
}

Time: O(n log n) to build, O(log n) per query · Extra space: O(n log n). The table has log n rows. Each question uses at most one jump per row.

Watch out for

  • Not making "no parent" point to a safe value (0 that points to itself), so look-ups crash on missing ancestors.
  • Building rows in the wrong order. Row j needs row j-1 finished first.
  • Using too few rows: LOG must be large enough that 2LOG is bigger than the deepest climb.

Quick check

  1. Which jumps do we use to climb 6 steps?
    • 2 and 4
    • 1 and 5
    • 3 and 3
  2. How is the 4-step ancestor built?
    • A fresh walk of 4 steps
    • Two 2-step jumps in a row
    • Sort the nodes
  3. Time for one k-th ancestor query?
    • O(k)
    • O(n)
    • O(log k)