Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

Augmented Search Trees

Subtree sizes for order statistics, interval trees and implicit keys.

A balanced BST answers "is 42 stored?" in O(log⁡n)O(\log n). Add one number per node, the size of its subtree, and it also answers "what is the 1000th smallest key?" and "how many keys are below 42?" in O(log⁡n)O(\log n), under insertions and deletions. The trick generalizes: any value that a node can compute from its children rides along with the tree almost for free.

What you’ll learn

  • State and prove the augmentation theorem: a field computable in O(1)O(1) from a node and its children survives insertions, deletions and rotations at O(log⁡n)O(\log n) cost per update.
  • Implement an order-statistic tree with select and rank, and prove both correct.
  • Build an interval tree with subtree maxima, prove that its search never misses an overlap, and bound the cost of reporting all kk overlaps.
  • Treat ranks as implicit keys, compare augmented trees with segment and Fenwick trees, and state the cell-probe limits of dynamic ranks and prefix sums.

The augmentation recipe

An augmented tree stores extra information in each node to answer new kinds of queries. CLRS (chapter 17) splits the design into four steps: choose an underlying structure (a red-black tree, a treap, …); choose the extra information; check that updates and rotations can maintain it; and write the new operations. The third step is where designs fail, and one theorem settles it for a large family of fields.

DerivationProof
  1. O(1)⋅(path length)=O(log⁡n)O(1)\cdot(\text{path length})=O(\log n)

    A change propagates only upward. f(x)f(x) depends only on xx's subtree, so inserting or removing a node yy invalidates ff exactly at yy's ancestors. Recomputing them bottom-up along one path costs

  2. ((α x β) y γ) ⟶ (α x (β y γ)):recompute f(y), then f(x)\big((\alpha\ x\ \beta)\ y\ \gamma\big)\ \longrightarrow\ \big(\alpha\ x\ (\beta\ y\ \gamma)\big):\quad\text{recompute } f(y),\ \text{then } f(x)

    A rotation changes two subtrees. Rotating at yy with child xx moves the middle subtree β\beta from xx to yy; every other node keeps exactly the same descendants. So only f(y)f(y) and f(x)f(x) change, and recomputing them, the lower node first, costs O(1)O(1):

  3. Tupdate=O(log⁡n)+O(#rotations)=O(log⁡n)T_{\text{update}}=O(\log n)+O(\#\text{rotations})=O(\log n)

    Total. Red-black insertion and deletion walk one path and make at most 2 and 3 rotations, so maintaining ff adds O(log⁡n)O(\log n). The same argument covers AVL trees, whose deletions may rotate O(log⁡n)O(\log n) times at O(1)O(1) each, and treaps, with an expected O(1)O(1) rotations:

FieldRecurrence at xxWhat it answers
Subtree size1+size(x.left)+size(x.right)1+\text{size}(x.left)+\text{size}(x.right)kk-th smallest key, rank of a key
Sum of valuesv(x)+sum(x.left)+sum(x.right)v(x)+\text{sum}(x.left)+\text{sum}(x.right)Sum of the values whose keys lie in a range
Minimum of valuesmin⁡(v(x), min⁡(x.left), min⁡(x.right))\min\big(v(x),\ \min(x.left),\ \min(x.right)\big)Minimum over a key range
Largest right endpointmax⁡(x.hi, x.left.max, x.right.max)\max\big(x.hi,\ x.left.max,\ x.right.max\big)Interval overlap (interval trees)
Height or colorFrom the children's heights or colorsBalancing itself is an augmentation
Each field combines the node's own value with its children's fields by an associative operation.
Check your understanding

Which field can not be maintained by this recipe in O(log⁡n)O(\log n) time per update?

  1. The number of keys in the subtree
  2. The depth of each node
  3. The sum of the keys in the subtree
  4. The largest key in the subtree
Show the answer

B. The depth of each node

Depth depends on a node's ancestors, not on its descendants: a single rotation at the root changes the depth of every node in two whole subtrees, Θ(n)\Theta(n) fields at once. The theorem needs fields that look down the tree, not up.

Order-statistic trees

Store x.sizex.size, the number of nodes in xx's subtree, and two new operations each walk one path: select(k) returns the key of rank kk (0-indexed, so k=0k=0 is the smallest) and rank(key) counts the stored keys smaller than key. The result is an order-statistic tree.

python
def size(x):
    return x.size if x else 0

def select(x, k):                  # the key of rank k (k = 0 is the smallest)
    while x is not None:
        s = size(x.left)
        if k < s:
            x = x.left
        elif k == s:
            return x.key
        else:
            k, x = k - s - 1, x.right
    raise IndexError('k out of range')

def rank(x, key):                  # how many stored keys are < key
    r = 0
    while x is not None:
        if key <= x.key:
            x = x.left
        else:
            r, x = r + size(x.left) + 1, x.right
    return r

Both run on any BST whose nodes keep size up to date. Tested on a size-augmented treap against a sorted list: random insertions and deletions, then select and rank queries.

DerivationWhy select and rank are correct
  1. select(x,k)={select(x.left, k)k<sx.keyk=sselect(x.right, k−s−1)k>s\text{select}(x,k)=\begin{cases}\text{select}(x.left,\ k) & k<s\\ x.key & k=s\\ \text{select}(x.right,\ k-s-1) & k>s\end{cases}

    Select. Invariant: the answer is the key of rank kk within the current subtree. At node xx with s=size(x.left)s=\text{size}(x.left), the left subtree holds ranks 0,…,s−10,\dots,s-1, the node holds rank ss, and the right subtree holds the rest, shifted by s+1s+1:

  2. rank(key)=∑x : the walk turns right at x(size(x.left)+1)\text{rank}(key)=\sum_{x\,:\ \text{the walk turns right at }x}\big(\text{size}(x.left)+1\big)

    Rank. Invariant: rr counts the stored keys smaller than key outside the current subtree. Turning right at xx passes xx and its whole left subtree, all smaller than key; turning left passes nothing smaller:

  3. Tselect=Trank=O(h)=O(log⁡n)T_{\text{select}}=T_{\text{rank}}=O(h)=O(\log n)

    Both walk one root-to-leaf path, and the augmentation theorem keeps the sizes correct, so in a balanced tree

Predict before you look

An order-statistic tree stores the integers 1,…,10001,\dots,1000 except the multiples of 10: 900 keys. What does rank(500) return, the number of stored keys smaller than 500?

Show the answer

450

The candidates below 500 are 1,…,4991,\dots,499, which is 499 numbers, and the 49 multiples 10,20,…,49010,20,\dots,490 are missing: 499−49=450499-49=450. The walk computes it from subtree sizes in O(log⁡n)O(\log n) steps without listing anything.

In C++, GCC's policy-based data structures provide exactly this tree: __gnu_pbds::tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> adds find_by_order(k) and order_of_key(x) to a red-black tree. It is a libstdc++ extension, so it is missing with clang's libc++, and Java and Python have no standard equivalent.

Typical uses: for each element, count the smaller elements to its right (scan from the right, ask rank, then insert); maintain the median of a sliding window (select of the middle rank); count inversions online. When every key is known in advance, a Fenwick tree over compressed values answers the same rank questions with smaller constants.

Interval trees

An interval tree, in CLRS's version, stores closed intervals [lo,hi][lo,hi] in a balanced BST keyed by lolo and augments every node with x.maxx.max, the largest hihi in its subtree, maintained by x.max=max⁡(x.hi, x.left.max, x.right.max)x.max=\max(x.hi,\ x.left.max,\ x.right.max). Two closed intervals [a,b][a,b] and [c,d][c,d] overlap exactly when a≤da\le d and c≤bc\le b.

python
def overlap_search(x, lo, hi):     # some stored [x.lo, x.hi] meeting [lo, hi], or None
    while x is not None and not (x.lo <= hi and lo <= x.hi):
        if x.left is not None and x.left.max >= lo:
            x = x.left             # if anything overlaps, something on the left does
        else:
            x = x.right            # nothing on the left can overlap
    return x

CLRS's INTERVAL-SEARCH. Tested on an augmented treap with random intervals against a brute-force scan.

DerivationProof
  1. ∃ overlap in T ⟹ ∃ overlap in the subtree of x\exists\ \text{overlap in } T\ \Longrightarrow\ \exists\ \text{overlap in the subtree of } x

    Invariant: if any stored interval overlaps the query, then one lies in the subtree of the current node xx. It holds at the root. Suppose xx itself does not overlap.

  2. x.left.max<lo ⟹ hi′<lo  for every [lo′,hi′] on the leftx.left.max<lo\ \Longrightarrow\ hi'<lo\ \text{ for every } [lo',hi'] \text{ on the left}

    Going right is safe. The walk goes right when the left subtree is empty or x.left.max<lox.left.max<lo. Then every interval on the left ends before the query starts, and none can overlap:

  3. lo′′ ≥ x.lo ≥ lo′ > hilo''\ \ge\ x.lo\ \ge\ lo'\ >\ hi

    Going left is safe too. The walk goes left when x.left.max≥lox.left.max\ge lo, so some interval [lo′,hi′][lo',hi'] on the left has hi′≥lohi'\ge lo. If it does not overlap the query, then lo′>hilo'>hi. Every interval [lo′′,hi′′][lo'',hi''] on the right starts even later, so none of them overlaps either; any overlap must be on the left:

Think first At node xx, which does not overlap the query [9,12][9,12], the left child has max=7max=7. Where does the search go, and why?

Right. Every interval in the left subtree ends by 7, before 9, so none overlaps [9,12][9,12]: if any stored interval overlaps the query, it is in the right subtree.

Reporting all kk overlapping intervals costs more. A traversal that skips every subtree with max<lomax<lo, and every right subtree of a node with lo>hilo>hi, visits O((k+1)log⁡n)O((k+1)\log n) nodes; with a plain scan as fallback that is O(min⁡(n,(k+1)log⁡n))O(\min(n,(k+1)\log n)). For O(log⁡n+k)O(\log n+k), use a static centered interval tree or McCreight's priority search tree (1985), which also supports insertions and deletions in O(log⁡n)O(\log n).

Implicit keys, and the limits

Implicit keys. If a tree's operations only ever compare positions with subtree sizes, it needs no keys at all: a node's key is its rank. Any augmented balanced tree then becomes a dynamic sequence that supports insertion and deletion at any position and aggregates over any block in O(log⁡n)O(\log n). The implicit treap of the lesson Random BSTs & Treaps is the usual contest implementation.

StructureUpdatesRange queryNotes
Prefix-sum arrayNone (static)O(1)O(1)Any change costs an O(n)O(n) rebuild
Fenwick treePoint updates at fixed positionsPrefix aggregates of invertible operations, O(log⁡n)O(\log n)Smallest and simplest
Segment treePoint and range updates at fixed positionsAny associative operation, O(log⁡n)O(\log n)Array-based; positions known in advance
Augmented balanced BST, implicit treapInsertion and deletion anywhereAny associative operation, O(log⁡n)O(\log n)Pointer-based; larger constants
Square-root decompositionAlmost anythingO(n)O(\sqrt n)A simple fallback
Choose the lightest structure whose updates match the problem: fixed positions favor Fenwick and segment trees, while insertions in the middle need a balanced tree.

Key takeaways

  • A field computable in O(1)O(1) from a node and its children survives insertions, deletions and rotations at O(log⁡n)O(\log n) per update, because changes affect only ancestors and a rotation changes only two subtrees. Depth is not such a field.
  • Subtree sizes give select and rank in O(log⁡n)O(\log n): the order-statistic tree, available in C++ as GCC's __gnu_pbds::tree.
  • An interval tree keyed by left endpoints and augmented with subtree maxima finds an overlapping interval in O(log⁡n)O(\log n) and never misses one; reporting all kk overlaps costs O((k+1)log⁡n)O((k+1)\log n), and priority search trees reach O(log⁡n+k)O(\log n+k).
  • With implicit keys an augmented tree becomes a dynamic sequence. For dynamic prefix sums, cell-probe bounds of Θ(log⁡n/log⁡(b/δ))\Theta\big(\log n/\log(b/\delta)\big) show that O(log⁡n)O(\log n) per operation is the right cost for word-sized updates.

Check yourself

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

Question 1

At node xx, select looks for rank k=6k=6 (0-indexed), and size(x.left) is 4. What happens next?

  1. Go left with k=6k=6
  2. Return xx's key
  3. Go right with k=1k=1
  4. Go right with k=2k=2
Show the answer

C. Go right with k=1k=1

The left subtree holds ranks 0 to 3 and xx holds rank 4, so rank 6 lies in the right subtree, where it becomes rank 6−4−1=16-4-1=1.

Question 2

Interval search commits to the left subtree as soon as x.left.max≥lox.left.max\ge lo, even though an overlap might seem possible on the right too. Why is that safe?

  1. Because the left subtree is smaller
  2. Because if nothing on the left overlaps, the interval ending at x.left.maxx.left.max must start after hihi, and every interval on the right starts later still
  3. Because intervals in a right subtree never overlap a query
  4. Because the tree is balanced
Show the answer

B. Because if nothing on the left overlaps, the interval ending at x.left.maxx.left.max must start after hihi, and every interval on the right starts later still

Some interval [lo′,hi′][lo',hi'] on the left has hi′≥lohi'\ge lo. If it misses the query, then lo′>hilo'>hi, and every interval on the right starts at a key ≥x.lo≥lo′>hi\ge x.lo\ge lo'>hi. So whenever an overlap exists at all, one exists on the left.

Question 3

For each element of an array of n=2⋅105n=2\cdot10^5 integers, you need the number of smaller elements to its right. Which approach fits?

  1. For each element, scan everything to its right
  2. Sort the array once and binary-search each element
  3. Scan from right to left: ask each element's rank in an order-statistic tree, then insert it
  4. A hash map from each value to its count
Show the answer

C. Scan from right to left: ask each element's rank in an order-statistic tree, then insert it

When you reach a[i]a[i], the tree holds exactly the elements to its right, and rank counts the smaller ones in O(log⁡n)O(\log n): O(nlog⁡n)O(n\log n) in all. A Fenwick tree over compressed values is the lighter alternative.

Question 4

What do cell-probe lower bounds say about maintaining prefix sums of nn word-sized numbers under updates?

  1. O(1)O(1) time per operation is possible with enough memory
  2. With updates as large as a word, some operations must cost Ω(log⁡n)\Omega(\log n) amortized, so augmented balanced trees and Fenwick trees are asymptotically optimal
  3. Ω(n)\Omega(\sqrt n) time per operation is necessary
  4. They apply only to comparison-based data structures
Show the answer

B. With updates as large as a word, some operations must cost Ω(log⁡n)\Omega(\log n) amortized, so augmented balanced trees and Fenwick trees are asymptotically optimal

Pătraşcu and Demaine (2004) proved a tight Θ(1+log⁡n/log⁡(b/δ))\Theta\big(1+\log n/\log(b/\delta)\big) amortized bound for δ\delta-bit updates on bb-bit words. For word-sized updates this is Θ(log⁡n)\Theta(\log n); for ±1\pm1 updates with b=Θ(log⁡n)b=\Theta(\log n), the dynamic-rank case, it is Θ(log⁡n/log⁡log⁡n)\Theta(\log n/\log\log n).

Further reading

  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 17.
  • M. de Berg, O. Cheong, M. van Kreveld & M. Overmars, Computational Geometry: Algorithms and Applications, 3rd ed. (Springer, 2008), chapter 10.
  • E. M. McCreight, "Priority search trees," SIAM Journal on Computing 14(2) (1985), 257–276.
  • M. Pătraşcu & E. D. Demaine, "Tight bounds for the partial-sums problem," Proceedings of the 15th ACM-SIAM Symposium on Discrete Algorithms (SODA) (2004), 20–29.
  • D. D. Sleator & R. E. Tarjan, "A data structure for dynamic trees," Journal of Computer and System Sciences 26(3) (1983), 362–391.