Skip to main content

Binary Lifting

Both problems ask you to climb from a node toward the root, and to do it for many queries. The only move the tree gives you is "go to the parent", so a climb of k steps costs k steps, every query.

Binary lifting is the fix for the first one: write k in binary, and climb by jumps of 2j instead. Precompute up[j][v], the 2jth ancestor of v, once. Then any climb is at most log n jumps, one per set bit of k.

The table builds itself, because a jump of 2j is two jumps of 2j-1:

up[j][v] = up[j - 1][up[j - 1][v]]

The jump table is needed only for 1483. The second problem gets its climb for free from the heap labels, as shown below.

Problem map

The hub: an explicit parent array​

Otto, your interviewer

1483. Kth Ancestor of a Tree Node​

1483. Kth Ancestor of a Tree Node

LeetCode
Hard

Walk Up

FIG. 1483 KTH ANCESTOR OF A TREE NODE● INTERACTIVE
visualization loads as you reach it
class TreeAncestor:
def __init__(self, n: int, parent: list[int]):
self.parent = parent
 
def getKthAncestor(self, node: int, k: int) -> int:
while k and node != -1:
node = self.parent[node]
k -= 1
return node
top ↑

The same climb, no table​

Otto, your interviewer

2509. Cycle Length Queries in a Tree​

2509. Cycle Length Queries in a Tree

LeetCode
Hard

DFS (Recursive, Full Walk)

FIG. 2509 CYCLE LENGTH QUERIES IN A TREE● INTERACTIVE
visualization loads as you reach it
class Solution:
def cycleLengthQueries(self, n: int, queries: list[list[int]]) -> list[int]:
"""TLE"""
 
def rec(node, depth):
nonlocal lca, p_depth, q_depth, lca_depth
if node >= 2**n:
return 0
left = rec(2 * node, depth + 1)
right = rec(2 * node + 1, depth + 1)
found = left + right + int(node == p) + int(node == q)
if not lca and found == 2:
lca = node
lca_depth = depth
if node == p:
p_depth = depth
if node == q:
q_depth = depth
return found
 
result = []
for p, q in queries:
p_depth = q_depth = lca_depth = -1
lca = None
rec(1, 0)
result.append(p_depth + q_depth - 2 * lca_depth + 1)
return result
top ↑

The two problems side by side:

ProblemParent linkJump sizePer queryExtra memory
1483 Kth Ancestor of a Tree Nodethe hubparent[v]2jfrom a precomputed tableO(log n)O(n log n)the jump table
2509 Cycle Length Queries in a Treefrom 1483label >> 11one shift per stepO(n)n is the number of levelsO(1)