TExcelTAD
Home › Data Structures: Hashing, Search Trees, B-Trees & Union-Find › Order-Statistic Trees: Select and Rank

Order-Statistic Trees: Select and Rank

A red-black tree answers "is kk present?" and "what comes after kk?" in O(lg⁡n)O(\lg n). It cannot answer "what is the 100th smallest key?" or "how many keys are smaller than kk?" faster than walking through them, which is Θ(n)\Theta(n) 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 O(1)O(1) 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 xx stores x.sizex.\textit{size}, the number of internal nodes in the subtree rooted at xx, including xx; the sentinel has size 0. So

x.size=x.left.size+x.right.size+1x.\textit{size} = x.\textit{left}.\textit{size} + x.\textit{right}.\textit{size} + 1

The rank of a node is its position in the inorder walk, counting from 1: the minimum has rank 1 and the maximum rank nn. Within the subtree of xx, the rank of xx itself is x.left.size+1x.\textit{left}.\textit{size} + 1.

Select and rank

text
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 r

OS-SELECT walks down, OS-RANK walks up, so both take O(h)=O(lg⁡n)O(h) = O(\lg n) time.

Why OS-RANK is correct. Invariant: at the start of each iteration, rr is the rank of xx within the subtree rooted at yy. It holds initially. When yy is a right child, every node of the parent's left subtree and the parent itself precede the subtree of yy in the inorder walk, so the rank within the parent's subtree grows by that many; when yy is a left child nothing precedes it within the larger subtree. When yy reaches the root, rr 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 O(lg⁡n)O(\lg n) extra work.
  • Rotations: only the two nodes involved change their subtrees. After LEFT-ROTATE(x)(x) with y=x.righty = x.\textit{right}, node yy has exactly the nodes that xx had, and xx is recomputed from its new children:
text
y.size = x.size
x.size = x.left.size + x.right.size + 1
  • Recolourings do not change sizes. So the insertion fix-up costs O(1)O(1) extra per rotation, at most two.
  • Deletion: after removing or moving node yy, walk from yy'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 O(lg⁡n)O(\lg n). 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.

python · try it yourself
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.

cpp · try it yourself
#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 i<ji < j with ai>aja_i > a_j. Processing the sequence left to right, the number of earlier elements greater than aja_j is (elements so far) minus (rank of aja_j among them). With an order-statistic tree each step costs O(lg⁡n)O(\lg n), so all inversions are counted in O(nlg⁡n)O(n \lg n), and, unlike the merge-sort method, the count is available after every prefix. The practice problem Count Inversions asks for the total.

python · try it yourself
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 n2/4n^2/4 inversions, since each of the (n2)\binom{n}{2} pairs is inverted with probability about 1/21/2.

Test yourself

At node xx the left subtree has size 5. OS-SELECT is looking for rank i=9i = 9 in xx's subtree. What happens next?

  1. return xx
  2. go left looking for rank 9
  3. go right looking for rank 3
  4. go right looking for rank 4

After LEFT-ROTATE(x)(x) with y=x.righty = x.right, which sizes must be recomputed?

  1. all ancestors of xx
  2. only xx and yy
  3. all nodes in yy's subtree
  4. none

What does OS-RANK add when the current node yy is the right child of its parent?

  1. nothing
  2. the size of the parent's left subtree plus 1
  3. the size of yy's left subtree
  4. the size of the parent's right subtree