Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

Cartesian Trees & Nearest Smaller Values

The tree hidden in a monotonic stack, and its link to range minimum queries.

Run the monotonic stack of the previous lessons and, without noticing, you build a tree. Its root is the minimum of the array, its subtrees are the trees of the parts on either side, and the smallest value in any range a[i..j]a[i..j] sits at the lowest common ancestor of ii and jj. This Cartesian tree ties together nearest smaller values, range minimum queries, lowest common ancestors and treaps.

What you’ll learn

  • Define the Cartesian tree of an array, and prove that it is the unique binary tree that is heap-ordered by value and has the array's order as its inorder walk.
  • Build it in O(n)O(n) with a stack, and prove that each element's parent is the larger of its two nearest smaller values.
  • Prove that a range minimum query is a lowest common ancestor query in the Cartesian tree, and use the reduction in both directions.
  • Count Cartesian tree shapes with Catalan numbers, and derive the 2n−O(log⁡n)2n - O(\log n)-bit lower bound for encoding range minima.
  • Explain treaps as Cartesian trees of (key, priority) pairs, and the expected depth of their nodes.

A tree hidden in an array

PositionValueParentLeft childRight child
05position 1 (value 2)nonenone
12position 4 (value 1)position 0 (value 5)position 3 (value 6)
28position 3 (value 6)nonenone
36position 1 (value 2)position 2 (value 8)none
41none: the rootposition 1 (value 2)position 6 (value 3)
59position 6 (value 3)nonenone
63position 4 (value 1)position 5 (value 9)position 7 (value 7)
77position 6 (value 3)nonenone
The Cartesian tree of [5,2,8,6,1,9,3,7][5, 2, 8, 6, 1, 9, 3, 7]. Read the parents down the column: 1,4,3,1,−,6,4,61, 4, 3, 1, -, 6, 4, 6.

So a Cartesian tree is a binary search tree on the positions and a min-heap on the values at once. The subtree of a node mm covers a contiguous range of positions, exactly the range in which a[m]a[m] is the minimum, bounded by mm's nearest smaller values on either side. That already hints at the monotonic stack.

Check your understanding

In the Cartesian tree of [5,2,8,6,1,9,3,7][5, 2, 8, 6, 1, 9, 3, 7], which value is the parent of the 6?

  1. 8
  2. 1
  3. 2
  4. 3
Show the answer

C. 2

The 6 lies left of the minimum 1, in the part [5,2,8,6][5, 2, 8, 6] whose minimum is 2; right of the 2 comes [8,6][8, 6], whose minimum is 6, so 6 is the 2's right child. Equivalently, 6's nearest smaller values are 2 on its left and 1 on its right, and its parent is the larger of the two.

Building it in linear time with a stack

Insert the elements from left to right. The right spine of the tree built so far, the path from the root that always follows right children, holds values that increase downward: it is exactly a monotonic stack. To insert a[i]a[i], pop the spine nodes larger than a[i]a[i]. Together they become the left subtree of ii, hanging from the last one popped. Then ii becomes the right child of the new top of the stack, or the root if the stack is empty.

python
def cartesian_tree(a):
    """Parent array of the Cartesian tree (distinct values; -1 marks the root)."""
    parent = [-1] * len(a)
    stack = []                               # the right spine, root at the bottom
    for i, x in enumerate(a):
        last = -1
        while stack and a[stack[-1]] > x:
            last = stack.pop()               # popped nodes end up below i
        if last != -1:
            parent[last] = i                 # the last one popped becomes i's left child
        if stack:
            parent[i] = stack[-1]            # i becomes the right child of the new top
        stack.append(i)
    return parent

O(n)O(n) time, since each index is pushed once and popped at most once. On [5,2,8,6,1,9,3,7][5, 2, 8, 6, 1, 9, 3, 7] it returns the parents [1,4,3,1,−1,6,4,6][1, 4, 3, 1, -1, 6, 4, 6] of the table above.

DerivationProof
  1. subtree⁡(i)=(PSV(i), NSV(i))\operatorname{subtree}(i) = \big(\mathrm{PSV}(i),\ \mathrm{NSV}(i)\big)

    The subtree of ii is the interval in which a[i]a[i] is the minimum. By induction on the recursive definition, it covers exactly the positions strictly between ii's nearest smaller values:

  2. p∈{PSV(i), NSV(i)}p \in \{\mathrm{PSV}(i),\ \mathrm{NSV}(i)\}

    The parent is an endpoint. The parent pp is smaller than a[i]a[i], and ii's interval is the whole part of pp's interval on one side of pp. So pp bounds ii's interval: p=PSV(i)p = \mathrm{PSV}(i) if ii is a right child, and p=NSV(i)p = \mathrm{NSV}(i) if ii is a left child.

  3. parent⁡(i)=arg max⁡{ a[PSV(i)], a[NSV(i)] }\operatorname{parent}(i) = \operatorname*{arg\,max}\big\{\,a[\mathrm{PSV}(i)],\ a[\mathrm{NSV}(i)]\,\big\}

    It is the larger one. Say a[PSV(i)]>a[NSV(i)]a[\mathrm{PSV}(i)] > a[\mathrm{NSV}(i)]. If the parent were NSV(i)\mathrm{NSV}(i), the interval of ii would be everything in the parent's interval to the left of the parent, which contains PSV(i)\mathrm{PSV}(i), a larger value than the parent's. But ii's interval stops just after PSV(i)\mathrm{PSV}(i). So the parent is PSV(i)\mathrm{PSV}(i), and symmetrically in the other case.

The stack construction and the theorem are one fact seen twice: when a[i]a[i] arrives, the spine nodes it pops are exactly the indices whose next smaller value is ii, and the top left on the stack is PSV(i)\mathrm{PSV}(i). All nearest smaller values can also be found in parallel: Berkman, Schieber and Vishkin (1993) computed them in O(log⁡log⁡n)O(\log \log n) time with optimal total work on a CRCW PRAM, and used them as a building block for other doubly logarithmic parallel algorithms.

Range minimum is lowest common ancestor

DerivationProof
  1. a[m]=min⁡subtree⁡(m) ≤ min⁡a[i..j]a[m] = \min \operatorname{subtree}(m) \ \le\ \min a[i..j]

    Let m=LCA(i,j)m = \mathrm{LCA}(i, j). Its subtree covers a contiguous range of positions containing ii and jj, hence all of i..ji..j, and a[m]a[m] is the minimum of its subtree.

  2. i≤m≤j⟹RMQ⁡(i,j)=mi \le m \le j \quad\Longrightarrow\quad \operatorname{RMQ}(i, j) = m

    And mm lies in i..ji..j: either mm is ii or jj, or ii and jj are in different subtrees of mm, the left one covering positions before mm and the right one positions after it.

Think first In the tree of the first step, built from [5,2,8,6,1,9,3,7][5, 2, 8, 6, 1, 9, 3, 7], find the lowest common ancestor of positions 2 and 5, and of positions 2 and 3. Do they agree with the range minima?

Position 2 (value 8) climbs through 6, 2 and 1, and position 5 (value 9) through 3 to 1, so their lowest common ancestor is the root, position 4, holding 1: the minimum of [8,6,1,9][8, 6, 1, 9]. Position 3 is position 2's parent, so the lowest common ancestor of 2 and 3 is position 3 itself, holding 6: the minimum of [8,6][8, 6].

The reduction also runs backward. A lowest common ancestor query on any rooted tree becomes a range minimum query on the depths recorded along an Euler tour of the tree, an array whose consecutive entries differ by exactly ±1\pm 1. Bender and Farach-Colton (2000) exploited that ±1\pm 1 property. Cut the depth array into blocks of 12log⁡2n\tfrac12 \log_2 n entries: there are only O(n)O(\sqrt{n}) different block shapes, so a table of every in-block answer for every shape fits in o(n)o(n) space, and a sparse table over the O(n/log⁡n)O(n / \log n) block minimums handles queries that span several blocks. Chaining the reductions gives the classic result:

RMQ  → Cartesian tree   LCA  → Euler tour   ±1 RMQ:O(n) preprocessing,O(1) per query.\text{RMQ} \;\xrightarrow{\ \text{Cartesian tree}\ }\; \text{LCA} \;\xrightarrow{\ \text{Euler tour}\ }\; \pm 1\ \text{RMQ}: \qquad O(n) \text{ preprocessing}, \quad O(1) \text{ per query}.

The Optimal lessons Lowest Common Ancestors and Sparse Tables & Square-Root Decomposition in the Trees topic develop both halves.

Counting shapes, and treaps

How much must a range minimum structure remember? Two arrays have the same answer to every range minimum query exactly when their Cartesian trees have the same shape (Fischer & Heun, 2011): the shape fixes every lowest common ancestor, and conversely the answers determine the root and then, recursively, both subtrees. The number of binary tree shapes with nn nodes is the Catalan number

Cn=1n+1(2nn)  ∼  4nπ n3/2.C_n = \frac{1}{n + 1}\binom{2n}{n} \;\sim\; \frac{4^n}{\sqrt{\pi}\, n^{3/2}}.

So a structure that answers range minimum queries without access to the array must use at least log⁡2Cn=2n−32log⁡2n−O(1)\log_2 C_n = 2n - \tfrac32 \log_2 n - O(1) bits in the worst case; for n=1000n = 1000 that is about 1984 bits. Fischer and Heun matched the bound with a structure of 2n+o(n)2n + o(n) bits that answers queries in O(1)O(1) time.

Predict before you look

How many different Cartesian tree shapes do the 5!=1205! = 120 orderings of five distinct values produce?

Show the answer

42 shapes

Every binary tree shape with 5 nodes occurs, and there are C5=16(105)=42C_5 = \tfrac16 \binom{10}{5} = 42 of them. So the 120 orderings fall into 42 classes with identical answers to every range minimum query. For n=1,2,3,4,5n = 1, 2, 3, 4, 5 the counts are 1,2,5,14,421, 2, 5, 14, 42.

A treap (Aragon & Seidel, 1989) is a Cartesian tree of (key, priority) pairs: a binary search tree by key and a heap by priority. Give every key an independent random priority and the tree has the shape of a binary search tree built by inserting the keys in random order, whatever order they actually arrive in. In a treap of nn keys, the kk-th smallest key has expected depth Hk+Hn−k+1−2≤2ln⁡nH_k + H_{n-k+1} - 2 \le 2 \ln n, where Hm=1+12+⋯+1mH_m = 1 + \tfrac12 + \dots + \tfrac1m, and an insertion or deletion performs fewer than two rotations in expectation (Seidel & Aragon, 1996). The Trees lesson Random BSTs & Treaps proves these bounds.

Key takeaways

  • The Cartesian tree of an array is the unique binary tree that is heap-ordered by value and has the array order as its inorder walk; each subtree covers the interval in which its root is the minimum.
  • A monotonic stack builds it in O(n)O(n): the stack is the right spine, and each node's parent is the larger of its two nearest smaller values.
  • Range minimum queries are lowest common ancestor queries in the Cartesian tree, and via Euler tours and ±1\pm 1 range minima both are solved with O(n)O(n) preprocessing and O(1)O(1) time per query.
  • Range minima determine only the tree's shape, one of CnC_n, so 2n−O(log⁡n)2n - O(\log n) bits are necessary and 2n+o(n)2n + o(n) suffice. A treap is a Cartesian tree with random priorities, whose nodes have expected depth at most 2ln⁡n2 \ln n.

Check yourself

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

Question 1

Which two properties determine the Cartesian tree of an array of distinct values uniquely?

  1. Heap order on the values, and the array order as the inorder walk
  2. Heap order on the values, and balance (subtree sizes differing by at most one)
  3. Binary-search-tree order on the values, and the array order as the preorder walk
  4. The array order as the inorder walk, and minimum height
Show the answer

A. Heap order on the values, and the array order as the inorder walk

Heap order forces the minimum to the root, and the inorder condition forces the positions before it into the left subtree and those after it into the right; induction does the rest. No balance is involved: a sorted array has a path as its Cartesian tree.

Question 2

In the Cartesian tree of distinct values, element a[i]a[i] has the nearest smaller value 4 on its left and 7 on its right. Which is its parent?

  1. The 4, because it is smaller
  2. The 7, because it is larger
  3. Whichever of the two is closer to ii
  4. Neither: the parent is always the global minimum
Show the answer

B. The 7, because it is larger

The parent is the larger of the two nearest smaller values. The 4 is an ancestor too, higher up: ii's subtree, the interval between the 4 and the 7, hangs below the 7, whose own subtree hangs below the 4.

Question 3

Why is the minimum of a[i..j]a[i..j] at the lowest common ancestor mm of positions ii and jj in the Cartesian tree?

  1. Because mm's subtree is a contiguous range where a[m]a[m] is the minimum, it contains all of i..ji..j, and mm itself lies between ii and jj
  2. Because the lowest common ancestor is always the root
  3. Because Cartesian trees are balanced
  4. Because the lowest common ancestor is the node nearest the midpoint of ii and jj
Show the answer

A. Because mm's subtree is a contiguous range where a[m]a[m] is the minimum, it contains all of i..ji..j, and mm itself lies between ii and jj

Subtrees cover contiguous ranges, so mm's subtree contains i..ji..j, and a[m]a[m] is at most the range's minimum. And mm lies in i..ji..j, because ii and jj sit in different subtrees of mm (or one of them is mm), so it attains that minimum.

Question 4

Why must any structure that answers every range minimum query on arrays of length nn, without access to the array, use about 2n2n bits in the worst case?

  1. Because it must store the nn values at 2 bits each
  2. Because a sparse table uses 2n2n entries
  3. Because the query answers determine the Cartesian tree's shape, there are CnC_n shapes, and log⁡2Cn=2n−O(log⁡n)\log_2 C_n = 2n - O(\log n)
  4. Because there are n2n^2 queries needing 2 bits each
Show the answer

C. Because the query answers determine the Cartesian tree's shape, there are CnC_n shapes, and log⁡2Cn=2n−O(log⁡n)\log_2 C_n = 2n - O(\log n)

Two arrays whose trees have different shapes differ on some query, so the structure must distinguish all CnC_n shapes, which takes at least log⁡2Cn\log_2 C_n bits. Fischer and Heun's structure meets this bound up to lower-order terms, with 2n+o(n)2n + o(n) bits and constant-time queries.

Further reading

  • J. Vuillemin, "A unifying look at data structures," Communications of the ACM 23(4) (1980), 229–239.
  • H. N. Gabow, J. L. Bentley & R. E. Tarjan, "Scaling and related techniques for geometry problems," Proceedings of the 16th ACM Symposium on Theory of Computing (1984), 135–143.
  • M. A. Bender & M. Farach-Colton, "The LCA problem revisited," LATIN 2000: Theoretical Informatics, LNCS 1776 (2000), 88–94.
  • J. Fischer & V. Heun, "Space-efficient preprocessing schemes for range minimum queries on static arrays," SIAM Journal on Computing 40(2) (2011), 465–492.
  • R. Seidel & C. R. Aragon, "Randomized search trees," Algorithmica 16 (1996), 464–497.