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 , where do you land after moving up ancestors?" Doing this naively, walking up one parent at a time, takes steps per query, which is slow if you need to answer many such queries with large . Binary lifting precomputes, for every node, where it lands after steps (powers of two), then answers any query by combining a handful of these precomputed jumps, the same way any integer can be written as a sum of powers of two.
says: the node reached from after steps is whatever you reach after steps from wherever steps already got you, doubling the jump length each time you already know the previous one. To answer " steps from ," write in binary and apply the jump table only for the powers of two that are set, in steps rather than .
Worked example
To find the ancestor 13 steps above node : in binary (). Look up the precomputed 8-step jump from to get node , then the precomputed 4-step jump from to get node , then the precomputed 1-step jump from , 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 time after an preprocessing step, rather than walking both nodes up one level at a time.
Binary lifting precomputes jumps of length for every node in a tree, then answers a " steps up" query by combining only the precomputed jumps matching 's binary digits, turning an walk into an lookup.
Discussion
💡 Discussion rules
- Ask and answer about this concept. Off-topic gets removed.
- No homework dumps. Show what you tried first.
- Corrections are welcome. Cite a source when you claim an error.
Loading discussion…
Related concepts
Practice in interviews
Further reading
- Competitive programming standard technique; see also sparse tables