Binary lifting is a method for answering lowest common ancestor (LCA) queries on a rooted tree. The LCA of two nodes is their deepest shared ancestor; once it is known, the path between the nodes can be split into their paths to and from that ancestor, enabling distance and other path queries. Straightforward approaches can take linear time per query: marking ancestors or climbing both nodes in parallel still requires work proportional to their depths. The key observation is that, after the nodes are brought to the same depth, their ancestor paths meet in a monotonic way: once a pair of ancestors is equal, all higher pairs are equal too.
The method uses a binary-search variant that tests jumps of successively smaller powers of two. A depth-first preprocessing pass records each node’s ancestors at distances 1, 2, 4, 8, and so on, with each larger jump built from two smaller ones. This takes O(n log n) time and space. For a query, first lift the deeper node to match the other’s depth; then lift both nodes together by the largest jumps that keep them distinct. Their parent at the end is the LCA, with an early return if the first lifting makes them equal. Each query takes O(log n), making the approach useful when many tree-path queries are needed. The implementation also notes that storing a fixed number of jumps per node can complicate adding new leaves later.
Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.