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 sits at the lowest common ancestor of and . 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 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 -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
| Position | Value | Parent | Left child | Right child |
|---|---|---|---|---|
| 0 | 5 | position 1 (value 2) | none | none |
| 1 | 2 | position 4 (value 1) | position 0 (value 5) | position 3 (value 6) |
| 2 | 8 | position 3 (value 6) | none | none |
| 3 | 6 | position 1 (value 2) | position 2 (value 8) | none |
| 4 | 1 | none: the root | position 1 (value 2) | position 6 (value 3) |
| 5 | 9 | position 6 (value 3) | none | none |
| 6 | 3 | position 4 (value 1) | position 5 (value 9) | position 7 (value 7) |
| 7 | 7 | position 6 (value 3) | none | none |
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 covers a contiguous range of positions, exactly the range in which is the minimum, bounded by 's nearest smaller values on either side. That already hints at the monotonic stack.
In the Cartesian tree of , which value is the parent of the 6?
- 8
- 1
- 2
- 3
Show the answer
C. 2
The 6 lies left of the minimum 1, in the part whose minimum is 2; right of the 2 comes , 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 , pop the spine nodes larger than . Together they become the left subtree of , hanging from the last one popped. Then becomes the right child of the new top of the stack, or the root if the stack is empty.
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 parenttime, since each index is pushed once and popped at most once. On it returns the parents of the table above.
The subtree of is the interval in which is the minimum. By induction on the recursive definition, it covers exactly the positions strictly between 's nearest smaller values:
The parent is an endpoint. The parent is smaller than , and 's interval is the whole part of 's interval on one side of . So bounds 's interval: if is a right child, and if is a left child.
It is the larger one. Say . If the parent were , the interval of would be everything in the parent's interval to the left of the parent, which contains , a larger value than the parent's. But 's interval stops just after . So the parent is , and symmetrically in the other case.
The stack construction and the theorem are one fact seen twice: when arrives, the spine nodes it pops are exactly the indices whose next smaller value is , and the top left on the stack is . All nearest smaller values can also be found in parallel: Berkman, Schieber and Vishkin (1993) computed them in 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
Let . Its subtree covers a contiguous range of positions containing and , hence all of , and is the minimum of its subtree.
And lies in : either is or , or and are in different subtrees of , the left one covering positions before and the right one positions after it.
Think first In the tree of the first step, built from , 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 . 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 .
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 . Bender and Farach-Colton (2000) exploited that property. Cut the depth array into blocks of entries: there are only different block shapes, so a table of every in-block answer for every shape fits in space, and a sparse table over the block minimums handles queries that span several blocks. Chaining the reductions gives the classic result:
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 nodes is the Catalan number
So a structure that answers range minimum queries without access to the array must use at least bits in the worst case; for that is about 1984 bits. Fischer and Heun matched the bound with a structure of bits that answers queries in time.
How many different Cartesian tree shapes do the orderings of five distinct values produce?
Show the answer
42 shapes
Every binary tree shape with 5 nodes occurs, and there are of them. So the 120 orderings fall into 42 classes with identical answers to every range minimum query. For the counts are .
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 keys, the -th smallest key has expected depth , where , 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 : 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 range minima both are solved with preprocessing and time per query.
- Range minima determine only the tree's shape, one of , so bits are necessary and suffice. A treap is a Cartesian tree with random priorities, whose nodes have expected depth at most .
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Which two properties determine the Cartesian tree of an array of distinct values uniquely?
- Heap order on the values, and the array order as the inorder walk
- Heap order on the values, and balance (subtree sizes differing by at most one)
- Binary-search-tree order on the values, and the array order as the preorder walk
- 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.
In the Cartesian tree of distinct values, element has the nearest smaller value 4 on its left and 7 on its right. Which is its parent?
- The 4, because it is smaller
- The 7, because it is larger
- Whichever of the two is closer to
- 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: 's subtree, the interval between the 4 and the 7, hangs below the 7, whose own subtree hangs below the 4.
Why is the minimum of at the lowest common ancestor of positions and in the Cartesian tree?
- Because 's subtree is a contiguous range where is the minimum, it contains all of , and itself lies between and
- Because the lowest common ancestor is always the root
- Because Cartesian trees are balanced
- Because the lowest common ancestor is the node nearest the midpoint of and
Show the answer
A. Because 's subtree is a contiguous range where is the minimum, it contains all of , and itself lies between and
Subtrees cover contiguous ranges, so 's subtree contains , and is at most the range's minimum. And lies in , because and sit in different subtrees of (or one of them is ), so it attains that minimum.
Why must any structure that answers every range minimum query on arrays of length , without access to the array, use about bits in the worst case?
- Because it must store the values at 2 bits each
- Because a sparse table uses entries
- Because the query answers determine the Cartesian tree's shape, there are shapes, and
- Because there are queries needing 2 bits each
Show the answer
C. Because the query answers determine the Cartesian tree's shape, there are shapes, and
Two arrays whose trees have different shapes differ on some query, so the structure must distinguish all shapes, which takes at least bits. Fischer and Heun's structure meets this bound up to lower-order terms, with 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.