Quant Memo
Advanced

Binary Lifting

A technique for answering 'what node do you reach after k steps up a tree' in logarithmic time, by precomputing jumps of length 1, 2, 4, 8... and combining them like binary digits of k.

Prerequisites: Lowest Common Ancestor

Given a tree where each node has a parent, a common question is: "starting from node vv, where do you land after moving up kk ancestors?" Doing this naively — walking up one parent at a time — takes O(k)O(k) steps per query, which is slow if you need to answer many such queries with large kk. Binary lifting precomputes, for every node, where it lands after 1,2,4,8,1, 2, 4, 8, \dots steps (powers of two), then answers any query by combining a handful of these precomputed jumps — the same way any integer kk can be written as a sum of powers of two.

up[v][j]=up[up[v][j1]][j1]\text{up}[v][j] = \text{up}\big[\, \text{up}[v][j-1] \,\big][j-1]

says: the node reached from vv after 2j2^j steps is whatever you reach after 2j12^{j-1} steps from wherever 2j12^{j-1} steps already got you — doubling the jump length each time you already know the previous one. To answer "kk steps from vv," write kk in binary and apply the jump table only for the powers of two that are set, in O(logk)O(\log k) steps rather than O(k)O(k).

Worked example

To find the ancestor 13 steps above node vv: 13=8+4+113 = 8 + 4 + 1 in binary (110121101_2). Look up the precomputed 8-step jump from vv to get node uu, then the precomputed 4-step jump from uu to get node ww, then the precomputed 1-step jump from ww — three table lookups total, instead of walking up 13 individual parent pointers one at a time.

This same doubling trick, applied with an LCA-finding rule at each level, is the standard way to answer lowest-common-ancestor queries in O(logn)O(\log n) time after an O(nlogn)O(n \log n) preprocessing step, rather than walking both nodes up one level at a time.

Binary lifting precomputes jumps of length 2j2^j for every node in a tree, then answers a "kk steps up" query by combining only the precomputed jumps matching kk's binary digits — turning an O(k)O(k) walk into an O(logk)O(\log k) lookup.

Related concepts

Practice in interviews

Further reading

  • Competitive programming standard technique; see also sparse tables
ShareTwitterLinkedIn