Augmented Search Trees
Subtree sizes for order statistics, interval trees and implicit keys.
A balanced BST answers "is 42 stored?" in . 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 , 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 from a node and its children survives insertions, deletions and rotations at 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 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.
A change propagates only upward. depends only on 's subtree, so inserting or removing a node invalidates exactly at 's ancestors. Recomputing them bottom-up along one path costs
A rotation changes two subtrees. Rotating at with child moves the middle subtree from to ; every other node keeps exactly the same descendants. So only and change, and recomputing them, the lower node first, costs :
Total. Red-black insertion and deletion walk one path and make at most 2 and 3 rotations, so maintaining adds . The same argument covers AVL trees, whose deletions may rotate times at each, and treaps, with an expected rotations:
| Field | Recurrence at | What it answers |
|---|---|---|
| Subtree size | -th smallest key, rank of a key | |
| Sum of values | Sum of the values whose keys lie in a range | |
| Minimum of values | Minimum over a key range | |
| Largest right endpoint | Interval overlap (interval trees) | |
| Height or color | From the children's heights or colors | Balancing itself is an augmentation |
Which field can not be maintained by this recipe in time per update?
- The number of keys in the subtree
- The depth of each node
- The sum of the keys in the subtree
- 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, fields at once. The theorem needs fields that look down the tree, not up.
Order-statistic trees
Store , the number of nodes in 's subtree, and two new operations each walk one path: select(k) returns the key of rank (0-indexed, so is the smallest) and rank(key) counts the stored keys smaller than key. The result is an order-statistic tree.
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 rBoth 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.
Select. Invariant: the answer is the key of rank within the current subtree. At node with , the left subtree holds ranks , the node holds rank , and the right subtree holds the rest, shifted by :
Rank. Invariant: counts the stored keys smaller than
keyoutside the current subtree. Turning right at passes and its whole left subtree, all smaller thankey; turning left passes nothing smaller:Both walk one root-to-leaf path, and the augmentation theorem keeps the sizes correct, so in a balanced tree
An order-statistic tree stores the integers 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 , which is 499 numbers, and the 49 multiples are missing: . The walk computes it from subtree sizes in 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 in a balanced BST keyed by and augments every node with , the largest in its subtree, maintained by . Two closed intervals and overlap exactly when and .
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 xCLRS's INTERVAL-SEARCH. Tested on an augmented treap with random intervals against a brute-force scan.
Invariant: if any stored interval overlaps the query, then one lies in the subtree of the current node . It holds at the root. Suppose itself does not overlap.
Going right is safe. The walk goes right when the left subtree is empty or . Then every interval on the left ends before the query starts, and none can overlap:
Going left is safe too. The walk goes left when , so some interval on the left has . If it does not overlap the query, then . Every interval on the right starts even later, so none of them overlaps either; any overlap must be on the left:
Think first At node , which does not overlap the query , the left child has . Where does the search go, and why?
Right. Every interval in the left subtree ends by 7, before 9, so none overlaps : if any stored interval overlaps the query, it is in the right subtree.
Reporting all overlapping intervals costs more. A traversal that skips every subtree with , and every right subtree of a node with , visits nodes; with a plain scan as fallback that is . For , use a static centered interval tree or McCreight's priority search tree (1985), which also supports insertions and deletions in .
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 . The implicit treap of the lesson Random BSTs & Treaps is the usual contest implementation.
| Structure | Updates | Range query | Notes |
|---|---|---|---|
| Prefix-sum array | None (static) | Any change costs an rebuild | |
| Fenwick tree | Point updates at fixed positions | Prefix aggregates of invertible operations, | Smallest and simplest |
| Segment tree | Point and range updates at fixed positions | Any associative operation, | Array-based; positions known in advance |
| Augmented balanced BST, implicit treap | Insertion and deletion anywhere | Any associative operation, | Pointer-based; larger constants |
| Square-root decomposition | Almost anything | A simple fallback |
Key takeaways
- A field computable in from a node and its children survives insertions, deletions and rotations at 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 : 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 and never misses one; reporting all overlaps costs , and priority search trees reach .
- With implicit keys an augmented tree becomes a dynamic sequence. For dynamic prefix sums, cell-probe bounds of show that 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.
At node , select looks for rank (0-indexed), and size(x.left) is 4. What happens next?
- Go left with
- Return 's key
- Go right with
- Go right with
Show the answer
C. Go right with
The left subtree holds ranks 0 to 3 and holds rank 4, so rank 6 lies in the right subtree, where it becomes rank .
Interval search commits to the left subtree as soon as , even though an overlap might seem possible on the right too. Why is that safe?
- Because the left subtree is smaller
- Because if nothing on the left overlaps, the interval ending at must start after , and every interval on the right starts later still
- Because intervals in a right subtree never overlap a query
- Because the tree is balanced
Show the answer
B. Because if nothing on the left overlaps, the interval ending at must start after , and every interval on the right starts later still
Some interval on the left has . If it misses the query, then , and every interval on the right starts at a key . So whenever an overlap exists at all, one exists on the left.
For each element of an array of integers, you need the number of smaller elements to its right. Which approach fits?
- For each element, scan everything to its right
- Sort the array once and binary-search each element
- Scan from right to left: ask each element's rank in an order-statistic tree, then insert it
- 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 , the tree holds exactly the elements to its right, and rank counts the smaller ones in : in all. A Fenwick tree over compressed values is the lighter alternative.
What do cell-probe lower bounds say about maintaining prefix sums of word-sized numbers under updates?
- time per operation is possible with enough memory
- With updates as large as a word, some operations must cost amortized, so augmented balanced trees and Fenwick trees are asymptotically optimal
- time per operation is necessary
- They apply only to comparison-based data structures
Show the answer
B. With updates as large as a word, some operations must cost amortized, so augmented balanced trees and Fenwick trees are asymptotically optimal
Pătraşcu and Demaine (2004) proved a tight amortized bound for -bit updates on -bit words. For word-sized updates this is ; for updates with , the dynamic-rank case, it is .
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.