Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

Lowest Common Ancestors

Binary lifting, Euler tours with range minimum, and Tarjan’s offline algorithm.

Which is the deepest node above both uu and vv? Walking up from both answers in O(n)O(n) per query. Storing ancestors at power-of-two distances answers in O(log⁡n)O(\log n); writing the tree out as an Euler tour turns the question into a range minimum, answered in O(1)O(1); and after O(n)O(n) preprocessing, O(1)O(1) per query is optimal on the word RAM. On a pointer machine it is not achievable at all, and in the space an index needs, the Catalan numbers set the limit.

What you’ll learn

  • Define lowest common ancestors and prove binary lifting correct, with O(nlog⁡n)O(n\log n) preprocessing and O(log⁡n)O(\log n) queries for LCA and kk-th ancestors.
  • Prove that the LCA is the shallowest node between the two first visits of an Euler tour, and answer queries in O(1)O(1) with a sparse table.
  • Explain the ±1\pm1 block decomposition that gives O(n)O(n) preprocessing and O(1)O(1) queries, and the equivalence of LCA and RMQ through Cartesian trees.
  • Prove Tarjan's offline algorithm correct, and state the lower bounds: Ω(log⁡log⁡n)\Omega(\log\log n) per query on a pointer machine, and log⁡2Cn≈2n\log_2 C_n\approx2n bits for an index-only RMQ structure.

The problem, and binary lifting

The naive method computes depths, lifts the deeper node until both have the same depth, then lifts both until they meet: ⟨O(n),O(h)⟩\langle O(n), O(h)\rangle, which is Θ(n)\Theta(n) per query on a path. Binary lifting stores jumps instead of single steps. Let up⁡j(v)\operatorname{up}_j(v) be the ancestor 2j2^j levels above vv, or the root if vv is not that deep. Then up⁡0\operatorname{up}_0 is the parent, and two jumps of 2j−12^{j-1} make one of 2j2^j:

up⁡j(v)=up⁡j−1(up⁡j−1(v)),0≤j<L=⌈log⁡2n⌉.\operatorname{up}_j(v)=\operatorname{up}_{j-1}\big(\operatorname{up}_{j-1}(v)\big),\qquad 0\le j<L=\big\lceil\log_2 n\big\rceil .

Any ancestor at distance kk is then reached by one jump per 1-bit of kk.

DerivationProof of the LCA query
  1. anc⁡a(anc⁡b(v))=anc⁡a+b(v)\operatorname{anc}_a\big(\operatorname{anc}_b(v)\big)=\operatorname{anc}_{a+b}(v)

    Equalize depths. Let anc⁡k(v)\operatorname{anc}_k(v) be the ancestor kk levels up. Jumps compose, so lifting the deeper node uu by d=depth⁡(u)−depth⁡(v)d=\operatorname{depth}(u)-\operatorname{depth}(v), one jump per 1-bit of dd, lands on anc⁡d(u)\operatorname{anc}_d(u). If that is vv, then vv is the answer.

  2. anc⁡k(u)=anc⁡k(v)  ⟺  k≥δ\operatorname{anc}_k(u)=\operatorname{anc}_k(v)\iff k\ge\delta

    The test. Otherwise u≠vu\ne v at equal depth. Let w=LCA⁡(u,v)w=\operatorname{LCA}(u,v) and δ≥1\delta\ge1 the distance from uu (and from vv) up to ww. Their ancestors at distance kk coincide exactly when they are at or above ww:

  3. δ−1<20 ⟹ δ=1 ⟹ LCA⁡(u,v)=up⁡0(u)\delta-1<2^0\ \Longrightarrow\ \delta=1\ \Longrightarrow\ \operatorname{LCA}(u,v)=\operatorname{up}_0(u)

    The descent. So up⁡j(u)≠up⁡j(v)\operatorname{up}_j(u)\ne\operatorname{up}_j(v) holds exactly when 2j<δ2^j<\delta. Scan jj from L−1L-1 down to 0 and jump both nodes whenever the test passes. Initially δ−1<2L\delta-1<2^L, and after level jj the remaining distance satisfies δ−1<2j\delta-1<2^j: a jump removes the bit 2j2^j, and no jump means it was already absent. After level 0:

  4. P(n)=O(nlog⁡n),Q(n)=O(log⁡n)P(n)=O(n\log n),\qquad Q(n)=O(\log n)

    Cost. The table has LL rows of nn entries, each computed in O(1)O(1); a query makes at most LL jumps per phase:

python
def preprocess(parent, root):              # parent[v] for every v != root; nodes 0..n-1
    n = len(parent)
    children = [[] for _ in range(n)]
    for v in range(n):
        if v != root:
            children[parent[v]].append(v)
    depth, order = [0] * n, [root]
    for v in order:                         # BFS order: parents before children
        for c in children[v]:
            depth[c] = depth[v] + 1
            order.append(c)
    up = [[root if v == root else parent[v] for v in range(n)]]
    for _ in range(max(1, (n - 1).bit_length()) - 1):
        prev = up[-1]
        up.append([prev[prev[v]] for v in range(n)])
    return depth, up

def lca(u, v, depth, up):
    if depth[u] < depth[v]:
        u, v = v, u
    d = depth[u] - depth[v]
    for j in range(len(up)):                # lift u by d, one bit at a time
        if d >> j & 1:
            u = up[j][u]
    if u == v:
        return u
    for j in reversed(range(len(up))):      # jump while the ancestors still differ
        if up[j][u] != up[j][v]:
            u, v = up[j][u], up[j][v]
    return up[0][u]

No recursion, so paths of any length are safe. Checked against the naive method on 400 random trees, including paths and stars. With the LCA, distances follow: dist⁡(u,v)=depth⁡(u)+depth⁡(v)−2depth⁡(w)\operatorname{dist}(u,v)=\operatorname{depth}(u)+\operatorname{depth}(v)-2\operatorname{depth}(w), with root distances in place of depths for weighted edges, and the kk-th node on the path from uu to vv is an ancestor of uu or of vv, one more lifting query.

Predict before you look

Binary lifting on a tree of n=105n=10^5 nodes. How many table entries up⁡j(v)\operatorname{up}_j(v) does the code above store, in millions?

Show the answer

1.7 million

n−1=99,999n-1=99{,}999 has 17 bits, so there are L=17L=17 rows of 10510^5 entries: 1.7×1061.7\times10^6. That is Θ(nlog⁡n)\Theta(n\log n) memory, about 7 MB as 4-byte integers and far more as Python lists, which is one reason to want the O(n)O(n)-space structures of the next screens.

Euler tours turn LCA into a range minimum

Run a depth-first search from the root and write down a node when it is first entered and again after returning from each of its children. This Euler tour, tour[0..2n−2]\mathrm{tour}[0..2n-2], has 2n−12n-1 entries, because each of the n−1n-1 edges adds one entry going down and one coming back. Record the depth ℓ[i]\ell[i] of each entry and the index first⁡(v)\operatorname{first}(v) of each node's first appearance. Consecutive depths differ by exactly ±1\pm1.

DerivationProof
  1. first⁡(u)≤i≤first⁡(v) ⟹ ℓ[i] ≥ depth⁡(w)\operatorname{first}(u)\le i\le\operatorname{first}(v)\ \Longrightarrow\ \ell[i]\ \ge\ \operatorname{depth}(w)

    The range stays inside ww's subtree. Let w=LCA⁡(u,v)w=\operatorname{LCA}(u,v). The search enters ww before reaching uu or vv and leaves ww for good only after finishing both, so every entry between the two first visits is a node of ww's subtree:

  2. ∃ i∈[first⁡(u),first⁡(v)]: tour[i]=w\exists\,i\in\big[\operatorname{first}(u),\operatorname{first}(v)\big]:\ \mathrm{tour}[i]=w

    The range contains ww. If u=wu=w, it does at first⁡(u)\operatorname{first}(u). Otherwise uu and vv lie below two different children of ww, since a single child would be a lower common ancestor; between finishing the first child's subtree and entering the second, the tour writes ww.

  3. min⁡iℓ[i]=depth⁡(w)andℓ[i]=depth⁡(w)⇒tour[i]=w\min_{i}\ell[i]=\operatorname{depth}(w)\quad\text{and}\quad \ell[i]=\operatorname{depth}(w)\Rightarrow \mathrm{tour}[i]=w

    Only ww is that shallow. Every other node of ww's subtree is strictly deeper than ww, so the minimum depth over the range is attained exactly at the copies of ww.

text
tree: A has children B, C;  B has D, E;  E has G, H;  C has F

index   0  1  2  3  4  5  6  7  8  9 10 11 12 13 14
tour    A  B  D  B  E  G  E  H  E  B  A  C  F  C  A
ℓ       0  1  2  1  2  3  2  3  2  1  0  1  2  1  0

first:  A 0   B 1   D 2   E 4   G 5   H 7   C 11   F 12

For LCA⁡(D,H)\operatorname{LCA}(D,H), scan ℓ[2..7]=2,1,2,3,2,3\ell[2..7]=2,1,2,3,2,3: the minimum, 1, sits at index 3, where tour[3]=B\mathrm{tour}[3]=B. For LCA⁡(H,F)\operatorname{LCA}(H,F), the range ℓ[7..12]\ell[7..12] reaches 0 at index 10, the root AA.

Check your understanding

A range-minimum structure returns only the minimum value, 1, for ℓ[2..7]\ell[2..7], not its position. How can you still name LCA⁡(D,H)\operatorname{LCA}(D,H)?

  1. It is the ancestor of DD at depth 1, which is BB
  2. It is tour[1]\mathrm{tour}[1], the entry at index 1 of the tour
  3. It is any node of depth 1, such as CC
  4. You cannot: the position of the minimum is required
Show the answer

A. It is the ancestor of DD at depth 1, which is BB

The LCA is an ancestor of DD, and DD has exactly one ancestor at each depth. So the minimum value pins it down: the ancestor of DD at depth 1, here BB, one level-ancestor query. Structures that return the argmin, such as the sparse table of the next screen, avoid the extra step.

Constant-time queries in linear space

Any range-minimum structure on ℓ\ell now answers LCA queries. A sparse table stores, for every start ii and every power of two 2j2^j, the position of the minimum of ℓ[i..i+2j−1]\ell[i..i+2^j-1], each computed from its two halves. A query [l,r][l,r] takes j=⌊log⁡2(r−l+1)⌋j=\lfloor\log_2(r-l+1)\rfloor and compares two windows of length 2j2^j that overlap but together cover the range. The overlap is harmless because the minimum is idempotent: min⁡(x,x)=x\min(x,x)=x.

python
def build_sparse(depths):
    m = len(depths)
    sp = [list(range(m))]                   # sp[j][i]: argmin of depths[i : i + 2**j]
    j = 1
    while (1 << j) <= m:
        prev, half = sp[-1], 1 << (j - 1)
        sp.append([min(prev[i], prev[i + half], key=depths.__getitem__)
                   for i in range(m - (1 << j) + 1)])
        j += 1
    return sp

def argmin(sp, depths, l, r):               # inclusive range, l <= r
    j = (r - l + 1).bit_length() - 1        # largest 2**j <= r - l + 1
    a, b = sp[j][l], sp[j][r - (1 << j) + 1]   # two windows covering [l, r]
    return a if depths[a] <= depths[b] else b

With the tour and the first visits, LCA⁡(u,v)=tour[argmin⁡(first⁡(u),first⁡(v))]\operatorname{LCA}(u,v)=\mathrm{tour}[\operatorname{argmin}(\operatorname{first}(u),\operatorname{first}(v))] after ordering the two indices: ⟨O(nlog⁡n),O(1)⟩\langle O(n\log n),O(1)\rangle, the usual contest choice. Checked against the naive method on the same 400 random trees.

DerivationProof: the ±1 trick
  1. O(mblog⁡mb)=O(m)O\Big(\frac{m}{b}\log\frac{m}{b}\Big)=O(m)

    Blocks. Cut ℓ\ell, of length m=2n−1m=2n-1, into blocks of b=⌈12log⁡2m⌉b=\lceil\tfrac12\log_2 m\rceil entries. Keep each block's minimum in an array MM of ⌈m/b⌉\lceil m/b\rceil entries, and build a sparse table on MM:

  2. 2 b−1 ≤ 212log⁡2m=m⟹O(m log⁡2m)=o(m)2^{\,b-1}\ \le\ 2^{\frac12\log_2 m}=\sqrt m\quad\Longrightarrow\quad O\big(\sqrt m\,\log^2 m\big)=o(m)

    Patterns. Inside a block every step is +1+1 or −1-1, so after subtracting the block's first entry, a block is one of at most 2b−12^{b-1} patterns, and where the minimum of any sub-range sits depends only on the pattern. Tabulate each pattern that occurs, with all of its O(b2)O(b^2) sub-ranges:

  3. P(n)=O(n),Q(n)=O(1)P(n)=O(n),\qquad Q(n)=O(1)

    Queries. A range inside one block is one table lookup. Otherwise it splits into a suffix of ll's block, the whole blocks strictly between, and a prefix of rr's block: two lookups and one sparse-table query on MM, then the smallest of three.

  4. 1024⋅112=123,904  pattern entries ≪ m1024\cdot11^2=123{,}904\ \text{ pattern entries}\ \ll\ m

    In numbers. For n=106n=10^6: m=1,999,999m=1{,}999{,}999, b=11b=11, at most 210=10242^{10}=1024 patterns with 11211^2 entries each, and 181,819181{,}819 block minima for the sparse table.

The reduction also runs backward. The Cartesian tree of an array AA has the position of the minimum at its root and the Cartesian trees of the two sides as its subtrees, and a stack builds it in O(n)O(n) (the Optimal lesson Cartesian Trees & Nearest Smaller Values). For l≤rl\le r, the position of the minimum of A[l..r]A[l..r] is the LCA of ll and rr in that tree: going down from the root, the first node whose position falls in [l,r][l,r] separates ll from rr, and it holds the minimum of its whole subtree (Gabow, Bentley & Tarjan, 1984). Composing the two reductions, RMQ on any array is also ⟨O(n),O(1)⟩\langle O(n),O(1)\rangle.

Offline queries: Tarjan’s algorithm

When all qq queries are known before the first answer is needed, a single depth-first search answers them all, with a union-find structure and no table at all (Tarjan, 1979). Each node starts as its own set. When a child's subtree is finished, it is merged into its parent's set, and the merged set is anchored at the parent. A query is answered when the search finishes the second of its two nodes.

python
def offline_lca(children, root, queries):   # queries: list of pairs (u, v)
    n = len(children)
    parent, size, anchor = list(range(n)), [1] * n, list(range(n))
    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]   # path halving
            x = parent[x]
        return x
    asked = [[] for _ in range(n)]
    for i, (u, v) in enumerate(queries):
        asked[u].append((v, i)); asked[v].append((u, i))
    done, ans = [False] * n, [None] * len(queries)
    def dfs(u):
        for c in children[u]:
            dfs(c)
            a, b = find(u), find(c)         # merge c's finished subtree into u's set
            if size[a] < size[b]: a, b = b, a
            parent[b], size[a] = a, size[a] + size[b]
            anchor[a] = u                   # the merged set hangs at u, still open
        done[u] = True
        for v, i in asked[u]:
            if done[v]:
                ans[i] = anchor[find(v)]
    dfs(root)
    return ans

Union by size with path halving. The recursion is hh deep, so on deep trees replace it with an explicit stack. Checked against the naive method on the same 400 random trees, 60 queries each.

DerivationWhy every answer is right
  1. S(w)={w} ∪⋃c a finished child of wsubtree⁡(c)S(w)=\{w\}\ \cup\bigcup_{c\ \text{a finished child of }w}\operatorname{subtree}(c)

    Invariant. While the search is at node xx, the finished nodes and the nodes on the root-to-xx path are partitioned into sets, one per node ww on that path, and each set is anchored at its ww:

  2. S(u)←S(u)∪S(c),anchor⁡←uS(u)\leftarrow S(u)\cup S(c),\qquad\operatorname{anchor}\leftarrow u

    It is maintained. When a child cc of uu finishes, its whole subtree is finished and forms S(c)S(c); merging it into S(u)S(u) and anchoring the result at uu restores the invariant.

  3. anchor⁡(find⁡(v))=LCA⁡(u,v)\operatorname{anchor}\big(\operatorname{find}(v)\big)=\operatorname{LCA}(u,v)

    The answer. When uu finishes, take a query (u,v)(u,v) with vv already finished. Then vv lies in S(w)S(w) for the deepest node ww of the root-to-uu path that is an ancestor of vv. The ancestors of uu are exactly that path, so ww is the deepest common ancestor. Each query is answered once, when the second of its nodes finishes.

The trade-off is the batch: the search answers queries in its own order, so it needs all of them up front. In return it uses O(n+q)O(n+q) memory instead of a table of nlog⁡nn\log n entries, which makes it the natural choice when the pairs come in one file, as in many offline algorithms.

Lower bounds and the frontier

MethodPreprocessingQuerySpaceNotes
Climb from both nodesO(n)O(n)O(h)O(h)O(n)O(n)Θ(n)\Theta(n) per query on a path
Binary liftingO(nlog⁡n)O(n\log n)O(log⁡n)O(\log n)O(nlog⁡n)O(n\log n) wordsAlso kk-th ancestors; extends to path minimums and sums
Euler tour + sparse tableO(nlog⁡n)O(n\log n)O(1)O(1)O(nlog⁡n)O(n\log n) wordsThe usual contest choice
Euler tour + ±1\pm1 blocksO(n)O(n)O(1)O(1)O(n)O(n) wordsOptimal on the RAM; larger constants
Tarjan's offline algorithmO((n+q) α(n))O((n+q)\,\alpha(n)) in totalanswered in batchO(n+q)O(n+q)All queries known in advance
Online methods are rated ⟨P(n),Q(n)⟩\langle P(n),Q(n)\rangle; the offline one by its total time for qq queries.
DerivationProof of the space bound
  1. root=RMQ⁡(0,n−1), then recurse on [0,root−1] and [root+1,n−1]\text{root}=\operatorname{RMQ}(0,n-1),\ \text{then recurse on }[0,\text{root}-1]\text{ and }[\text{root}+1,n-1]

    The answers determine the Cartesian tree. Its root is the position of the minimum of the whole array, and its subtrees are the Cartesian trees of the two sides, found recursively by further queries:

  2. Cn=1n+1(2nn)C_n=\frac{1}{n+1}\binom{2n}{n}

    Every shape occurs. List the nodes of any binary tree in inorder and give each the value n⋅depth+positionn\cdot\text{depth}+\text{position}. The values are distinct and each subtree's root holds its subtree's smallest value, so the Cartesian tree of this array is the tree itself. The Cartesian tree in turn fixes every answer, since an RMQ is an LCA in it, so answer tables and shapes correspond one to one:

  3. log⁡2Cn=2n−32log⁡2n−log⁡2π+o(1)\log_2 C_n=2n-\tfrac32\log_2 n-\log_2\sqrt\pi+o(1)

    Count bits. A structure that never reads the array must tell all these tables apart from its own memory. By Stirling's formula:

  4. log⁡2C106≈1,999,969\log_2 C_{10^6}\approx1{,}999{,}969

    For n=106n=10^6 that is about 1,999,9691{,}999{,}969 bits, two bits per element. Fischer and Heun (2011) match it up to lower-order terms, with 2n+o(n)2n+o(n) bits and O(1)O(1)-time queries.

Key takeaways

  • Binary lifting stores the 2j2^j-th ancestors: ⟨O(nlog⁡n),O(log⁡n)⟩\langle O(n\log n),O(\log n)\rangle for LCA and kk-th-ancestor queries, correct because ancestors at distance kk coincide exactly when kk reaches the distance to the LCA.
  • An Euler tour turns LCA into a range minimum over depths between two first visits; a sparse table gives ⟨O(nlog⁡n),O(1)⟩\langle O(n\log n),O(1)\rangle, and because consecutive depths differ by ±1\pm1, blocks of 12log⁡2n\tfrac12\log_2 n entries have at most n\sqrt n patterns, which gives ⟨O(n),O(1)⟩\langle O(n),O(1)\rangle.
  • Through Cartesian trees, RMQ and LCA reduce to each other, so both are ⟨O(n),O(1)⟩\langle O(n),O(1)\rangle on the word RAM.
  • Offline, Tarjan's depth-first search with union-find answers qq queries in O((n+q) α(n))O((n+q)\,\alpha(n)) time and O(n+q)O(n+q) space, in linear time with Gabow and Tarjan's union-find.
  • The limits: a pointer machine needs Ω(log⁡log⁡n)\Omega(\log\log n) per query, and an index-only RMQ structure needs log⁡2Cn≈2n\log_2 C_n\approx2n bits, which Fischer and Heun match up to o(n)o(n).

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In the second phase of binary lifting, u≠vu\ne v at equal depth, and both jump by 2j2^j only when up⁡j(u)≠up⁡j(v)\operatorname{up}_j(u)\ne\operatorname{up}_j(v). Why not jump when the two ancestors are equal?

  1. An equal pair may lie strictly above the LCA, so the jump could overshoot it
  2. Equal ancestors mean that u=vu=v already
  3. Jumping on equality would raise the query time to Θ(log⁡2n)\Theta(\log^2 n)
  4. It would also be correct, but it would need a third phase
Show the answer

A. An equal pair may lie strictly above the LCA, so the jump could overshoot it

Ancestors at distance kk coincide exactly when k≥δk\ge\delta, the distance to the LCA. An equal pair says only that 2j≥δ2^j\ge\delta: the common node could be the LCA or anything above it. Jumping only while they differ keeps both nodes strictly below the LCA, so the loop ends at two of its children.

Question 2

Why is the shallowest entry of the Euler tour between first⁡(u)\operatorname{first}(u) and first⁡(v)\operatorname{first}(v) the LCA ww?

  1. The tour lists the nodes in order of increasing depth
  2. Between those visits the tour stays inside ww's subtree and passes through ww, the only node of its depth there
  3. The two first visits are at most log⁡2n\log_2 n entries apart
  4. The root appears between any two first visits
Show the answer

B. Between those visits the tour stays inside ww's subtree and passes through ww, the only node of its depth there

The search cannot leave ww's subtree while either uu or vv is still unfinished, and it returns to ww between the two children's subtrees that contain uu and vv (or starts at w=uw=u). Within ww's subtree, ww is strictly the shallowest node.

Question 3

Which situation calls for Tarjan's offline algorithm rather than a sparse table over the Euler tour?

  1. Each query must be answered before the next one is read
  2. Edges are linked and cut between queries
  3. All qq queries are given in advance, and memory for a table of nlog⁡nn\log n entries is short
  4. The input is a DAG, in which a pair can have several lowest common ancestors
Show the answer

C. All qq queries are given in advance, and memory for a table of nlog⁡nn\log n entries is short

The depth-first search answers each query when it finishes the second of its two nodes, so it must know every query up front. In exchange it needs only O(n+q)O(n+q) memory and O((n+q) α(n))O((n+q)\,\alpha(n)) time, linear with Gabow and Tarjan's union-find.

Question 4

An RMQ index on nn distinct numbers answers every query without ever reading the array. Why must it use about 2n2n bits?

  1. Each element's value needs 2 bits
  2. A sparse table needs nlog⁡nn\log n bits
  3. The pointer-machine bound Ω(log⁡log⁡n)\Omega(\log\log n) forces it
  4. Its answers determine the array's Cartesian tree, and there are Cn≈4n/(n3/2π)C_n\approx4^n/(n^{3/2}\sqrt\pi) possible shapes
Show the answer

D. Its answers determine the array's Cartesian tree, and there are Cn≈4n/(n3/2π)C_n\approx4^n/(n^{3/2}\sqrt\pi) possible shapes

The answers to all queries fix the Cartesian tree's shape, and every shape occurs, so the index must distinguish CnC_n cases: log⁡2Cn=2n−32log⁡2n−O(1)\log_2 C_n=2n-\tfrac32\log_2 n-O(1) bits. Fischer and Heun's structure uses 2n+o(n)2n+o(n) bits, so the bound is tight up to lower-order terms.

Further reading

  • D. Harel & R. E. Tarjan, "Fast algorithms for finding nearest common ancestors," SIAM Journal on Computing 13(2) (1984), 338–355.
  • B. Schieber & U. Vishkin, "On finding lowest common ancestors: simplification and parallelization," SIAM Journal on Computing (1988).
  • R. E. Tarjan, "Applications of path compression on balanced trees," Journal of the ACM 26(4) (1979), 690–715.
  • M. A. Bender & M. Farach-Colton, "The LCA problem revisited," LATIN 2000, LNCS 1776 (Springer, 2000), 88–94.
  • J. Fischer & V. Heun, "Space-efficient preprocessing schemes for range minimum queries on static arrays," SIAM Journal on Computing (2011).