Graph Theory37 sections · 1633 units
Open in Course

Core Idea - Binary Search for LCA

(Jump both simultaneously)

Once aa and bb are at the same depth, jump both upward simultaneously in powers of 22. For each jj from logn\log n down to 00, check if up[a][j] != up[b][j].

If so, jump both: a = up[a][j], b = up[b][j]. After all jumps, aa and bb are directly below the LCA. The LCA is up[a][0] (or up[b][0], same thing). You try large jumps first and only make a jump if it does not overshoot the LCA.