Data Structures19 sections · 729 units
Open in Course

LCA with Sparse Table

Euler tour + RMQ

Lowest Common Ancestor you can reduce to RMQ using Euler tour. The Euler tour visits each node when entering and after visiting each child. Record:

  • euler[]: sequence of nodes in tour
  • depth[]: depth of each node in tour
  • first[]: first occurrence of each node in tour For LCA of nodes uu and vv:

1.1. Find first occurrences: i=first[u]i = \text{first}[u], j=first[v]j = \text{first}[v]

2.2. Query for minimum depth in range [min(i,j),max(i,j)][\min(i,j), \max(i,j)]

3.3. The node at that minimum depth position is the LCA This reduces LCA to RMQ, giving O(1)O(1) LCA queries after O(nlogn)O(n \log n) preprocessing.