Mini Project: An Ordered Map with Order Statistics
Python's dict finds a key in expected time but knows nothing about order: "the 10th smallest key", "how many keys are below 500", "the median" all cost a sort. C++'s std::map keeps keys in order, but it cannot jump to the -th one either. In this project you build the structure that does all of it in : an ordered map on a red-black tree whose nodes also store their subtree sizes, the order-statistic tree with deletion added.
The project puts the whole course to work: red-black insertion and deletion, the augmentation theorem for the sizes, and invariant checks after every operation. Each step is a complete program; later steps repeat the pieces they need, so you can run any of them on its own. Random choices use fixed seeds, so you get exactly the output shown.
Step 1: Insertion, lookup, select and rank
The class stores key-value pairs. put inserts a new key or replaces the value of an existing one, maintaining the sizes on the way down and in every rotation. select(i) returns the pair of rank (1-based), and rank(key) the number of keys smaller than key, which works whether or not key is stored. The demo stores the prices of a few products and asks order questions about them.
RED, BLACK = "R", "B"
class Node:
__slots__ = ("key", "value", "color", "left", "right", "parent", "size")
def __init__(self, key, value, color, nil, size=1):
self.key, self.value, self.color, self.size = key, value, color, size
self.left = self.right = self.parent = nil
class OrderedMap:
def __init__(self):
self.nil = Node(None, None, BLACK, None, size=0) # shared sentinel with size 0
self.root = self.nil
def __len__(self):
return self.root.size
def _pull(self, x):
x.size = x.left.size + x.right.size + 1
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
self._pull(x); self._pull(y)
def get(self, key, default=None):
x = self.root
while x is not self.nil and x.key != key:
x = x.left if key < x.key else x.right
return default if x is self.nil else x.value
def put(self, key, value):
y, x = self.nil, self.root
while x is not self.nil:
if key == x.key:
x.value = value # existing key: replace the value
return
y, x = x, (x.left if key < x.key else x.right)
z = Node(key, value, RED, self.nil)
z.parent = y
if y is self.nil: self.root = z
elif key < y.key: y.left = z
else: y.right = z
a = y
while a is not self.nil: # one more node below every ancestor
a.size += 1; a = a.parent
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
def select(self, i):
if not 1 <= i <= len(self):
raise IndexError(i)
x = self.root
while True:
r = x.left.size + 1
if i == r: return x.key, x.value
if i < r: x = x.left
else: i, x = i - r, x.right
def rank(self, key): # number of stored keys < key
r, x = 0, self.root
while x is not self.nil:
if key <= x.key: x = x.left
else: r, x = r + x.left.size + 1, x.right
return r
prices = OrderedMap()
for price, item in [(349, "monitor"), (25, "mouse"), (79, "keyboard"), (1299, "laptop"),
(15, "cable"), (189, "headset"), (59, "webcam"), (899, "tablet"), (49, "hub")]:
prices.put(price, item)
prices.put(79, "mechanical keyboard") # same key: the value is replaced
n = len(prices)
print("items:", n, "| price 79 is", prices.get(79))
print("cheapest:", prices.select(1), "| most expensive:", prices.select(n))
print("median price:", prices.select((n + 1) // 2))
print("items under 100:", prices.rank(100), "| items from 50 to 500:", prices.rank(501) - prices.rank(50))
print("3rd most expensive:", prices.select(n - 2))items: 9 | price 79 is mechanical keyboard
cheapest: (15, 'cable') | most expensive: (1299, 'laptop')
median price: (79, 'mechanical keyboard')
items under 100: 5 | items from 50 to 500: 4
3rd most expensive: (349, 'monitor')
The counts are differences of ranks: the keys in are those smaller than minus those smaller than (for integer keys). Every query is one walk from the root.
Step 2: Deletion, and a test that trusts nothing
Deletion is RB-DELETE with one addition for the sizes. After the structural change, every node from the old position of the moved or removed node up to the root has lost one node from its subtree; those are exactly the ancestors of , so the program recomputes the size of each of them, starting at x.parent (which RB-TRANSPLANT sets even when is the sentinel). The fix-up's rotations then keep the sizes right through _rotate.
The test is the point of this step. It performs random puts and deletes on 60 maps, and after every operation it checks the red-black properties, the parent pointers, every size field, the key order, and a random select and rank against a plain dictionary and a sorted list of its keys.
import random, bisect
RED, BLACK = "R", "B"
class Node:
__slots__ = ("key", "value", "color", "left", "right", "parent", "size")
def __init__(self, key, value, color, nil, size=1):
self.key, self.value, self.color, self.size = key, value, color, size
self.left = self.right = self.parent = nil
class OrderedMap:
def __init__(self):
self.nil = Node(None, None, BLACK, None, size=0)
self.root = self.nil
def __len__(self):
return self.root.size
def _pull(self, x):
x.size = x.left.size + x.right.size + 1
def _rotate(self, x, d):
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
self._pull(x); self._pull(y)
def _find(self, key):
x = self.root
while x is not self.nil and x.key != key:
x = x.left if key < x.key else x.right
return x
def put(self, key, value):
y, x = self.nil, self.root
while x is not self.nil:
if key == x.key:
x.value = value; return
y, x = x, (x.left if key < x.key else x.right)
z = Node(key, value, RED, self.nil)
z.parent = y
if y is self.nil: self.root = z
elif key < y.key: y.left = z
else: y.right = z
a = y
while a is not self.nil:
a.size += 1; a = a.parent
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
def _transplant(self, u, v):
if u.parent is self.nil: self.root = v
elif u is u.parent.left: u.parent.left = v
else: u.parent.right = v
v.parent = u.parent # also for the sentinel
def delete(self, key):
z = self._find(key)
if z is self.nil:
raise KeyError(key)
nil = self.nil
y, y_color = z, z.color
if z.left is nil:
x = z.right; self._transplant(z, z.right)
elif z.right is nil:
x = z.left; self._transplant(z, z.left)
else:
y = z.right
while y.left is not nil: y = y.left
y_color, x = y.color, y.right
if y is not z.right:
self._transplant(y, y.right)
y.right = z.right; y.right.parent = y
else:
x.parent = y
self._transplant(z, y)
y.left = z.left; y.left.parent = y; y.color = z.color
a = x.parent # the ancestors of x lost one node
while a is not nil:
self._pull(a); a = a.parent
if y_color == BLACK:
while x is not self.root and x.color == BLACK:
a, b = ("left", "right") if x is x.parent.left else ("right", "left")
w = getattr(x.parent, b)
if w.color == RED:
w.color = BLACK; x.parent.color = RED
self._rotate(x.parent, a); w = getattr(x.parent, b)
if getattr(w, a).color == BLACK and getattr(w, b).color == BLACK:
w.color = RED; x = x.parent
else:
if getattr(w, b).color == BLACK:
getattr(w, a).color = BLACK; w.color = RED
self._rotate(w, b); w = getattr(x.parent, b)
w.color = x.parent.color
x.parent.color = BLACK; getattr(w, b).color = BLACK
self._rotate(x.parent, a); x = self.root
x.color = BLACK
def select(self, i):
x = self.root
while True:
r = x.left.size + 1
if i == r: return x.key, x.value
if i < r: x = x.left
else: i, x = i - r, x.right
def rank(self, key):
r, x = 0, self.root
while x is not self.nil:
if key <= x.key: x = x.left
else: r, x = r + x.left.size + 1, x.right
return r
def check(self):
"""asserts every red-black property, parent pointers and sizes; returns the keys in order"""
out = []
def walk(x, lo, hi):
if x is self.nil: return 1
assert (lo is None or lo < x.key) and (hi is None or x.key < hi), "order"
if x.color == RED: assert x.left.color == BLACK and x.right.color == BLACK, "red-red"
for c in (x.left, x.right): assert c is self.nil or c.parent is x, "parent"
assert x.size == x.left.size + x.right.size + 1, "size"
bl = walk(x.left, lo, x.key); out.append(x.key); br = walk(x.right, x.key, hi)
assert bl == br, "black height"
return bl + (x.color == BLACK)
assert self.root.color == BLACK and self.nil.color == BLACK and self.nil.size == 0
walk(self.root, None, None)
return out
rng = random.Random(1)
ops = deletes = 0
for trial in range(60):
m, ref = OrderedMap(), {}
for step in range(200):
k = rng.randrange(100)
if k in ref and rng.random() < 0.5:
m.delete(k); del ref[k]; deletes += 1
else:
m.put(k, step); ref[k] = step
ops += 1
keys = m.check()
assert keys == sorted(ref) and len(m) == len(ref)
if keys:
i = rng.randrange(1, len(keys) + 1)
assert m.select(i) == (keys[i - 1], ref[keys[i - 1]])
q = rng.randrange(110)
assert m.rank(q) == bisect.bisect_left(keys, q)
print(f"{ops} operations ({deletes} deletions) on 60 maps: every check passed after every operation")
try:
m.delete(1000)
except KeyError as e:
print("deleting a missing key raises KeyError:", e)12000 operations (2741 deletions) on 60 maps: every check passed after every operation
deleting a missing key raises KeyError: 1000
Step 3: A sliding-window median
A classic use of an order-statistic map: a stream of measurements arrives, and after each one you want the median of the last values, for example to smooth sensor readings while ignoring outliers. Each step inserts one value and deletes the one that left the window, then selects the middle rank: three operations. Values can repeat, so the map uses the pair (value, position) as its key, which makes every key distinct while keeping the order of the values.
The program computes the sliding medians of 3000 noisy readings with window 101, checks every one of them against sorting the window directly, and compares the work: the tree's comparisons per step against the element moves a sorted Python list would need for the same insertions and deletions.
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.size = key, color, size
self.left = self.right = self.parent = nil
class OrderedSet:
"""the map of step 2 without values; counts key comparisons"""
def __init__(self):
self.nil = Node(None, BLACK, None, size=0)
self.root, self.comparisons = self.nil, 0
def __len__(self):
return self.root.size
def _pull(self, x):
x.size = x.left.size + x.right.size + 1
def _rotate(self, x, d):
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
self._pull(x); self._pull(y)
def add(self, key):
y, x = self.nil, self.root
while x is not self.nil:
self.comparisons += 1
y, x = x, (x.left if key < x.key else x.right)
z = Node(key, RED, self.nil)
z.parent = y
if y is self.nil: self.root = z
elif key < y.key: y.left = z
else: y.right = z
a = y
while a is not self.nil:
a.size += 1; a = a.parent
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
def _transplant(self, u, v):
if u.parent is self.nil: self.root = v
elif u is u.parent.left: u.parent.left = v
else: u.parent.right = v
v.parent = u.parent
def remove(self, key):
z = self.root
while z.key != key:
self.comparisons += 1
z = z.left if key < z.key else z.right
nil = self.nil
y, y_color = z, z.color
if z.left is nil:
x = z.right; self._transplant(z, z.right)
elif z.right is nil:
x = z.left; self._transplant(z, z.left)
else:
y = z.right
while y.left is not nil: y = y.left
y_color, x = y.color, y.right
if y is not z.right:
self._transplant(y, y.right)
y.right = z.right; y.right.parent = y
else:
x.parent = y
self._transplant(z, y)
y.left = z.left; y.left.parent = y; y.color = z.color
a = x.parent
while a is not nil:
self._pull(a); a = a.parent
if y_color == BLACK:
while x is not self.root and x.color == BLACK:
a, b = ("left", "right") if x is x.parent.left else ("right", "left")
w = getattr(x.parent, b)
if w.color == RED:
w.color = BLACK; x.parent.color = RED
self._rotate(x.parent, a); w = getattr(x.parent, b)
if getattr(w, a).color == BLACK and getattr(w, b).color == BLACK:
w.color = RED; x = x.parent
else:
if getattr(w, b).color == BLACK:
getattr(w, a).color = BLACK; w.color = RED
self._rotate(w, b); w = getattr(x.parent, b)
w.color = x.parent.color
x.parent.color = BLACK; getattr(w, b).color = BLACK
self._rotate(x.parent, a); x = self.root
x.color = BLACK
def select(self, i):
x = self.root
while True:
r = x.left.size + 1
if i == r: return x.key
if i < r: x = x.left
else: i, x = i - r, x.right
rng = random.Random(2024)
readings = [round(20 + 5 * (i / 3000) + rng.gauss(0, 1) + (40 if rng.random() < 0.02 else 0), 1) for i in range(3000)]
w = 101
window, medians, moves, sorted_window = OrderedSet(), [], 0, []
for i, v in enumerate(readings):
window.add((v, i))
j = bisect.bisect_left(sorted_window, (v, i)); moves += len(sorted_window) - j
sorted_window.insert(j, (v, i))
if i >= w:
old = (readings[i - w], i - w)
window.remove(old)
j = bisect.bisect_left(sorted_window, old); moves += len(sorted_window) - j - 1
sorted_window.pop(j)
if i >= w - 1:
med = window.select((w + 1) // 2)[0]
assert med == sorted(readings[i - w + 1:i + 1])[w // 2]
medians.append(med)
steps = len(readings)
print(f"{len(medians)} window medians, all equal to sorting the window directly")
print("first medians:", medians[:5], "| last:", medians[-3:])
print("largest reading:", max(readings), "| largest median:", max(medians), "(the spikes are filtered out)")
print(f"tree: {window.comparisons / steps:.1f} comparisons per step; sorted list: {moves / steps:.1f} element moves per step")2900 window medians, all equal to sorting the window directly
first medians: [20.2, 20.3, 20.2, 20.2, 20.2] | last: [25.0, 25.0, 25.0]
largest reading: 66.0 | largest median: 25.1 (the spikes are filtered out)
tree: 10.3 comparisons per step; sorted list: 98.4 element moves per step
The median ignores the spikes completely: they are far fewer than half of any window. The tree spends about ten comparisons per step (one insertion and one deletion, each a walk down a tree of about 100 keys), while the sorted list moves about a hundred elements per step, half the window for each insertion and for each deletion. With a window of a million values the list's moves grow ten-thousandfold, while the tree needs only a few dozen more comparisons.
Step 4: The core in C++, against the standard library
The C++ version has the same operations on an index-based tree with a free list. The program runs 300,000 seeded random puts and deletes against std::map, and every 10,000 operations compares 100 random select and rank queries with a sorted snapshot of the keys; at the end it verifies the red-black properties and the sizes, and prints the height.
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <map>
#include <random>
#include <stdexcept>
#include <vector>
class OrderedMap {
struct Node { int key = 0, value = 0; bool red = false; int left = 0, right = 0, parent = 0, size = 0; };
std::vector<Node> t{Node{}}; // t[0]: black sentinel, size 0
std::vector<int> free_;
int root = 0;
int& child(int x, bool right) { return right ? t[x].right : t[x].left; }
void pull(int x) { t[x].size = t[t[x].left].size + t[t[x].right].size + 1; }
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;
pull(x); pull(y);
}
void transplant(int u, int v) {
if (t[u].parent == 0) root = v;
else if (u == t[t[u].parent].left) t[t[u].parent].left = v;
else t[t[u].parent].right = v;
t[v].parent = t[u].parent;
}
int find(int key) const {
int x = root;
while (x != 0 && t[x].key != key) x = key < t[x].key ? t[x].left : t[x].right;
return x;
}
int check(int x, long lo, long hi, int depth, int& height) const {
if (x == 0) { height = std::max(height, depth - 1); return 1; }
const Node& n = t[x];
if (n.key <= lo || n.key >= hi) throw std::runtime_error("order");
if (n.red && (t[n.left].red || t[n.right].red)) throw std::runtime_error("red-red");
if (n.size != t[n.left].size + t[n.right].size + 1) throw std::runtime_error("size");
int bl = check(n.left, lo, n.key, depth + 1, height), br = check(n.right, n.key, hi, depth + 1, height);
if (bl != br) throw std::runtime_error("black height");
return bl + !n.red;
}
public:
int size() const { return t[root].size; }
void put(int key, int value) {
int y = 0, x = root;
while (x != 0) {
if (key == t[x].key) { t[x].value = value; return; }
y = x; x = key < t[x].key ? t[x].left : t[x].right;
}
int z;
if (!free_.empty()) { z = free_.back(); free_.pop_back(); } else { z = static_cast<int>(t.size()); t.emplace_back(); }
t[z] = {key, value, true, 0, 0, y, 1};
if (y == 0) root = z; else if (key < t[y].key) t[y].left = z; else t[y].right = z;
for (int a = y; a != 0; a = t[a].parent) ++t[a].size;
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;
}
bool erase(int key) {
int z = find(key);
if (z == 0) return false;
int y = z, x;
bool y_red = t[y].red;
if (t[z].left == 0) { x = t[z].right; transplant(z, t[z].right); }
else if (t[z].right == 0) { x = t[z].left; transplant(z, t[z].left); }
else {
y = t[z].right;
while (t[y].left != 0) y = t[y].left;
y_red = t[y].red; x = t[y].right;
if (y != t[z].right) { transplant(y, t[y].right); t[y].right = t[z].right; t[t[y].right].parent = y; }
else t[x].parent = y;
transplant(z, y);
t[y].left = t[z].left; t[t[y].left].parent = y; t[y].red = t[z].red;
}
for (int a = t[x].parent; a != 0; a = t[a].parent) pull(a); // the ancestors of x lost one node
if (!y_red) {
while (x != root && !t[x].red) {
bool left = x == t[t[x].parent].left;
int w = child(t[x].parent, left);
if (t[w].red) { t[w].red = false; t[t[x].parent].red = true; rotate(t[x].parent, left); w = child(t[x].parent, left); }
if (!t[t[w].left].red && !t[t[w].right].red) { t[w].red = true; x = t[x].parent; }
else {
if (!t[child(w, left)].red) {
t[child(w, !left)].red = false; t[w].red = true;
rotate(w, !left); w = child(t[x].parent, left);
}
t[w].red = t[t[x].parent].red;
t[t[x].parent].red = false; t[child(w, left)].red = false;
rotate(t[x].parent, left); x = root;
}
}
t[x].red = false;
}
free_.push_back(z);
return true;
}
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 key) const { // number of keys < key
int r = 0, x = root;
while (x != 0) {
if (key <= t[x].key) x = t[x].left;
else { r += t[t[x].left].size + 1; x = t[x].right; }
}
return r;
}
int verified_height() const {
if (t[root].red || t[0].red || t[0].size != 0) throw std::runtime_error("root or sentinel");
int h = -1;
check(root, -1, 1L << 40, 0, h);
return h;
}
};
int main() {
OrderedMap m;
std::map<int, int> ref;
std::mt19937 rng(2024);
long bad = 0, checks = 0;
for (int step = 1; step <= 300000; ++step) {
int k = static_cast<int>(rng() % 100000);
if (rng() % 3 != 0) { m.put(k, step); ref[k] = step; }
else bad += m.erase(k) != (ref.erase(k) == 1);
bad += m.size() != static_cast<int>(ref.size());
if (step % 10000 == 0) { // compare select and rank with a snapshot
std::vector<int> sorted;
for (auto& kv : ref) sorted.push_back(kv.first);
for (int q = 0; q < 100; ++q) {
int i = 1 + static_cast<int>(rng() % sorted.size()), key = static_cast<int>(rng() % 100000);
bad += m.select(i) != sorted[i - 1];
bad += m.rank(key) != static_cast<int>(std::lower_bound(sorted.begin(), sorted.end(), key) - sorted.begin());
checks += 2;
}
}
}
int n = m.size(), h = m.verified_height();
std::printf("300000 updates, %ld select/rank checks, %ld disagreements\n", checks, bad);
std::printf("n = %d, height %d (2 lg(n+1) = %.1f), median key %d\n", n, h, 2 * std::log2(n + 1.0), m.select((n + 1) / 2));
}300000 updates, 6000 select/rank checks, 0 disagreements
n = 63150, height 19 (2 lg(n+1) = 31.9), median key 50026
std::map would need a linear walk with std::next for the median; this map finds it in one descent. (GCC also ships a non-standard order-statistic tree in its policy-based data structures, __gnu_pbds::tree with tree_order_statistics_node_update, built on the same idea.)
Ideas to extend the map
- Add
floor(key)andceiling(key)(largest key and smallest key a query) and an in-order iterator using TREE-SUCCESSOR. - Add
delete_rank(i), which removes the -th smallest key, and use it to implement the Josephus problem (remove every -th person from a circle) in . - Store the sum of values in each subtree as a second augmented field, and answer "total value of all keys in " in .
- Replace the red-black tree by a treap (a BST that is a heap on random priorities) with the same interface, and compare its height and rotation counts with the red-black version on the same operations.
- Count rotations per operation and check the bounds from the lessons: at most 2 per insertion and 3 per deletion.
Test yourself
The map holds the keys 10, 20, ..., 100. What do rank(55) and select(3) return?
- 5 and 30
- 6 and 30
- 5 and 20
- 55 and 3
After the structural part of a deletion, which sizes must be recomputed?
- all sizes in the tree
- the sizes of the ancestors of , from
x.parentup to the root - only the size of the root
- none: rotations fix them
Why does the sliding-window median use the key (value, position) instead of the value alone?
- To sort by position
- Because values repeat, and a map needs distinct keys; adding the position keeps the order of the values and makes each key unique
- Because tuples are faster
- To find the oldest value