progress

~/problems / Tree techniques / Binary lifting / LCA

Build the jump table

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Every binary-lifting trick (k-th ancestor, LCA) starts with one table: up[j][v] is the node 2^j steps up from v. Row 0 is the parent; each later row doubles the one before (2^j steps is 2^(j-1) steps, twice).

You get a rooted forest as parent (-1 for a root; parents needn't have smaller numbers). Implement build_jump_table(parent) -> list[list[int]] returning exactly LOG = n.bit_length() rows of length n:

  • up[0][v] = parent[v];
  • up[j][v] = up[j-1][ up[j-1][v] ], or -1 once the walk runs off the top.
# chain 0 <- 1 <- 2 <- 3 <- 4   (0 is the root)
build_jump_table([-1, 0, 1, 2, 3])
# [[-1, 0, 1, 2, 3],     1 step up
#  [-1, -1, 0, 1, 2],    2 steps up
#  [-1, -1, -1, -1, 0]]  4 steps up
The chain 4, 3, 2, 1, 0 drawn left to right with 0 as the root: the 4-step jump from node 4 to node 0 is two 2-step jumps, 4 to 2 and then 2 to 0.

1 <= n <= 10^5; there may be several roots.

⭐ Bonus: a speed test on a 100,000-node chain earns a star if each row is built from the previous one in O(n).

Show hint

build rows in order j = 1, 2, ...; each reads only the row before, so node order doesn't matter.

Topic: Binary lifting / LCA. up[k][v] = 2^k-th ancestor; LCA and k-th ancestor in O(log n).

0:00
Ctrl ' run · Ctrl ↵ submit
esc