Order-Statistic Trees: Select and Rank
A red-black tree answers "is present?" and "what comes after ?" in . It cannot answer "what is the 100th smallest key?" or "how many keys are smaller than ?" faster than walking through them, which is in the worst case. Yet both questions are natural: the median of a changing set, a player's position in a leaderboard, the number of inversions in a sequence.
The fix is to store one extra number in every node: the size of its subtree. With it, both queries become a single walk from the root, and the extra field costs only work per rotation to maintain. The result is an order-statistic tree. The selection problem for a fixed array was solved in Randomized Quickselect; this structure solves it for a set that changes.
The size field
Each node stores , the number of internal nodes in the subtree rooted at , including ; the sentinel has size 0. So
The rank of a node is its position in the inorder walk, counting from 1: the minimum has rank 1 and the maximum rank . Within the subtree of , the rank of itself is .
Select and rank
OS-SELECT(x, i) // the node of rank i in the subtree of x, 1 <= i <= x.size
1 while true
2 r = x.left.size + 1 // rank of x within its subtree
3 if i == r return x
4 elseif i < r x = x.left
5 else i = i - r, x = x.right // skip x and its left subtree
OS-RANK(T, x) // the rank of node x in the whole tree
1 r = x.left.size + 1
2 y = x
3 while y != T.root
4 if y == y.parent.right
5 r = r + y.parent.left.size + 1 // the parent and its left subtree come first
6 y = y.parent
7 return rOS-SELECT walks down, OS-RANK walks up, so both take time.
Why OS-RANK is correct. Invariant: at the start of each iteration, is the rank of within the subtree rooted at . It holds initially. When is a right child, every node of the parent's left subtree and the parent itself precede the subtree of in the inorder walk, so the rank within the parent's subtree grows by that many; when is a left child nothing precedes it within the larger subtree. When reaches the root, is the rank in the whole tree.
Maintaining the sizes
The sizes must stay correct through insertions, deletions and the fix-up rotations.
- Insertion, first phase: the new node gets size 1, and every node on the path from the root to it gains one node in its subtree: add 1 to each while walking down. That is extra work.
- Rotations: only the two nodes involved change their subtrees. After LEFT-ROTATE with , node has exactly the nodes that had, and is recomputed from its new children:
y.size = x.size
x.size = x.left.size + x.right.size + 1- Recolourings do not change sizes. So the insertion fix-up costs extra per rotation, at most two.
- Deletion: after removing or moving node , walk from 's old position up to the root and subtract 1 from each size; the deletion fix-up's rotations update sizes as above. Both cost . The mini project implements deletion with sizes.
The program adds the size field to the red-black insertion of Red-Black Insertion, checks every size and every answer against a sorted list, and then answers a few queries.
import random, bisect
RED, BLACK = "R", "B"
class Node:
__slots__ = ("key", "color", "left", "right", "parent", "size")
def __init__(self, key, color, nil, size=1):
self.key, self.color, self.left, self.right, self.parent, self.size = key, color, nil, nil, nil, size
class OSTree:
def __init__(self):
self.nil = Node(None, BLACK, None, size=0)
self.root = self.nil
def rotate(self, x, d): # d == "left": x's right child moves up
nil, o = self.nil, ("right" if d == "left" else "left")
y = getattr(x, o)
setattr(x, o, getattr(y, d))
if getattr(y, d) is not nil: getattr(y, d).parent = x
y.parent = x.parent
if x.parent is nil: self.root = y
elif x is x.parent.left: x.parent.left = y
else: x.parent.right = y
setattr(y, d, x)
x.parent = y
y.size = x.size # the two size updates
x.size = x.left.size + x.right.size + 1
def insert(self, key):
z, y, x = Node(key, RED, self.nil), self.nil, self.root
new = z
while x is not self.nil:
x.size += 1 # z will be in this subtree
y, x = x, (x.left if key < x.key else x.right)
z.parent = y
if y is self.nil: self.root = z
elif key < y.key: y.left = z
else: y.right = z
while z.parent.color == RED:
p = z.parent; g = p.parent
a, b = ("left", "right") if p is g.left else ("right", "left")
u = getattr(g, b)
if u.color == RED:
p.color = u.color = BLACK; g.color = RED; z = g; continue
if z is getattr(p, b):
z = p; self.rotate(z, a); p = z.parent
p.color = BLACK; g.color = RED; self.rotate(g, b)
self.root.color = BLACK
return new
def select(self, i):
x = self.root
while True:
r = x.left.size + 1
if i == r: return x
if i < r: x = x.left
else: i, x = i - r, x.right
def rank(self, x):
r, y = x.left.size + 1, x
while y is not self.root:
if y is y.parent.right:
r += y.parent.left.size + 1
y = y.parent
return r
def check_sizes(self, x=None):
x = self.root if x is None else x
if x is self.nil: return 0
s = self.check_sizes(x.left) + self.check_sizes(x.right) + 1
assert x.size == s, f"size of {x.key} is {x.size}, should be {s}"
return s
rng = random.Random(21)
t, keys, nodes = OSTree(), [], {}
for k in rng.sample(range(10 ** 6), 3000):
nodes[k] = t.insert(k)
bisect.insort(keys, k)
if len(keys) % 500 == 0:
t.check_sizes()
assert all(t.select(i).key == keys[i - 1] for i in range(1, len(keys) + 1, 7))
assert all(t.rank(nodes[k]) == bisect.bisect_left(keys, k) + 1 for k in keys[::11])
print("sizes, select and rank agree with a sorted list at n = 500, 1000, ..., 3000")
n = t.root.size
print("n =", n, "| median (rank", (n + 1) // 2, "):", t.select((n + 1) // 2).key, "=", keys[(n + 1) // 2 - 1])
k = keys[1234]
print(f"rank of {k}: {t.rank(nodes[k])} | 10th smallest: {t.select(10).key} | largest: {t.select(n).key}")sizes, select and rank agree with a sorted list at n = 500, 1000, ..., 3000
n = 3000 | median (rank 1500 ): 504574 = 504574
rank of 415531: 1235 | 10th smallest: 3335 | largest: 999113
In C++
The C++ version has the same structure on an index-based tree. It inserts 200,000 seeded random keys and then answers select and rank queries for a sample of ranks, checking them against a sorted copy.
#include <algorithm>
#include <cstdio>
#include <random>
#include <vector>
class OSTree {
struct Node { int key = 0; bool red = false; int left = 0, right = 0, parent = 0, size = 0; };
std::vector<Node> t{Node{}}; // t[0]: black sentinel with size 0
int root = 0;
int& child(int x, bool right) { return right ? t[x].right : t[x].left; }
void rotate(int x, bool left) { // left: x's right child moves up
int y = child(x, left);
child(x, left) = child(y, !left);
if (child(y, !left) != 0) t[child(y, !left)].parent = x;
t[y].parent = t[x].parent;
if (t[x].parent == 0) root = y;
else if (x == t[t[x].parent].left) t[t[x].parent].left = y;
else t[t[x].parent].right = y;
child(y, !left) = x;
t[x].parent = y;
t[y].size = t[x].size;
t[x].size = t[t[x].left].size + t[t[x].right].size + 1;
}
public:
int insert(int key) {
int y = 0, x = root;
while (x != 0) { ++t[x].size; y = x; x = key < t[x].key ? t[x].left : t[x].right; }
t.push_back({key, true, 0, 0, y, 1});
int z = static_cast<int>(t.size()) - 1, made = z;
if (y == 0) root = z; else if (key < t[y].key) t[y].left = z; else t[y].right = z;
while (t[t[z].parent].red) {
int p = t[z].parent, g = t[p].parent;
bool left = p == t[g].left;
int u = child(g, left);
if (t[u].red) { t[p].red = t[u].red = false; t[g].red = true; z = g; continue; }
if (z == child(p, left)) { z = p; rotate(z, left); p = t[z].parent; }
t[p].red = false; t[g].red = true;
rotate(g, !left);
}
t[root].red = false;
return made;
}
int select(int i) const { // key of rank i (1-based)
int x = root;
for (;;) {
int r = t[t[x].left].size + 1;
if (i == r) return t[x].key;
if (i < r) x = t[x].left; else { i -= r; x = t[x].right; }
}
}
int rank(int x) const {
int r = t[t[x].left].size + 1;
for (int y = x; y != root; y = t[y].parent)
if (y == t[t[y].parent].right) r += t[t[t[y].parent].left].size + 1;
return r;
}
int size() const { return t[root].size; }
};
int main() {
OSTree tree;
std::mt19937 rng(21);
std::vector<int> keys, handle;
for (int i = 0; i < 200000; ++i) keys.push_back(i * 7 + 3);
std::shuffle(keys.begin(), keys.end(), rng);
for (int k : keys) handle.push_back(tree.insert(k));
std::vector<int> sorted = keys;
std::sort(sorted.begin(), sorted.end());
bool ok = true;
for (int i = 1; i <= tree.size(); i += 997) ok = ok && tree.select(i) == sorted[i - 1];
for (std::size_t j = 0; j < keys.size(); j += 1009)
ok = ok && tree.rank(handle[j]) == static_cast<int>(std::lower_bound(sorted.begin(), sorted.end(), keys[j]) - sorted.begin()) + 1;
std::printf("n = %d, select and rank agree with the sorted keys: %s\n", tree.size(), ok ? "yes" : "no");
std::printf("median: %d, rank of the node holding %d: %d\n", tree.select((tree.size() + 1) / 2), keys[0], tree.rank(handle[0]));
}n = 200000, select and rank agree with the sorted keys: yes
median: 699996, rank of the node holding 1234579: 176369
An application: counting inversions online
An inversion of a sequence is a pair of positions with . Processing the sequence left to right, the number of earlier elements greater than is (elements so far) minus (rank of among them). With an order-statistic tree each step costs , so all inversions are counted in , and, unlike the merge-sort method, the count is available after every prefix. The practice problem Count Inversions asks for the total.
import random
class Node:
__slots__ = ("key", "left", "right", "size", "prio")
def __init__(self, key, prio):
self.key, self.left, self.right, self.size, self.prio = key, None, None, 1, prio
# A compact stand-in for the red-black tree above: a treap (a BST that is also a heap on random
# priorities), which keeps expected height O(lg n). Only insert and "count keys < k" are needed.
def size(x): return x.size if x else 0
def insert(x, key, prio):
if x is None: return Node(key, prio)
if key < x.key:
x.left = insert(x.left, key, prio)
if x.left.prio > x.prio: # rotate right
y = x.left; x.left, y.right = y.right, x; x.size = size(x.left) + size(x.right) + 1; x = y
else:
x.right = insert(x.right, key, prio)
if x.right.prio > x.prio: # rotate left
y = x.right; x.right, y.left = y.left, x; x.size = size(x.left) + size(x.right) + 1; x = y
x.size = size(x.left) + size(x.right) + 1
return x
def count_less(x, k): # the rank query: keys smaller than k
c = 0
while x:
if k <= x.key: x = x.left
else: c, x = c + size(x.left) + 1, x.right
return c
rng = random.Random(5)
a = [rng.randrange(1000) for _ in range(2000)]
root, inversions, history = None, 0, []
for j, v in enumerate(a):
inversions += j - count_less(root, v + 1) # earlier elements greater than v
root = insert(root, v, rng.random())
history.append(inversions)
brute = sum(a[i] > a[j] for i in range(300) for j in range(i + 1, 300))
print("inversions in the first 300 elements:", history[299], "(brute force:", brute, ")")
print("inversions in all 2000 elements:", inversions, "| about n^2/4 =", 2000 ** 2 // 4)inversions in the first 300 elements: 22287 (brute force: 22287 )
inversions in all 2000 elements: 1012365 | about n^2/4 = 1000000
The counts for every prefix come out of the same pass. A random sequence has about inversions, since each of the pairs is inverted with probability about .
Test yourself
At node the left subtree has size 5. OS-SELECT is looking for rank in 's subtree. What happens next?
- return
- go left looking for rank 9
- go right looking for rank 3
- go right looking for rank 4
After LEFT-ROTATE with , which sizes must be recomputed?
- all ancestors of
- only and
- all nodes in 's subtree
- none
What does OS-RANK add when the current node is the right child of its parent?
- nothing
- the size of the parent's left subtree plus 1
- the size of 's left subtree
- the size of the parent's right subtree