Ordered sets and maps: floor, ceiling, range queries
Balanced trees power ordered sets and maps that answer floor, ceiling and range queries. Watch an in-order walk visit only the range.
Before you start: Red-black trees.
The idea
An ordered map keeps its keys sorted. It can find the next key above 45, or every key from 25 to 55.
A hash map answers whether 45 is stored but has no order. A search tree uses its sorted shape to answer both questions.
Intuition
The floor of 45 is the largest key at most 45. The ceiling is the smallest key at least 45.
A balanced tree such as a red-black tree keeps its height small. Each query then costs about log n steps.
Java's TreeMap is a red-black tree. It offers floorKey, ceilingKey and subMap.
Complexity
A range query costs O(h + k): walk down to the range, then visit the k keys inside. Floor and ceiling cost O(h).
The height h is about log n in a balanced tree. In a plain chain h is n, so balancing matters.
Pitfalls
Floor and ceiling allow equal keys. If 40 is stored, both floor(40) and ceiling(40) are 40.
Strictly smaller or strictly larger is a different query, often called lower and higher.
Variations
The same tree gives the minimum, the maximum and the next key after any key. Treaps and splay trees do this too.
Code
Pseudocode
walk(root)
procedure walk(node)
if node = null: return
if node.val > lo: walk(node.left)
if lo ≤ node.val ≤ hi: report node.val
if node.val < hi: walk(node.right)
Python
def range_keys(root, lo, hi):
out = []
def walk(node):
if node is None:
return
if node.val > lo:
walk(node.left)
if lo <= node.val <= hi:
out.append(node.val)
if node.val < hi:
walk(node.right)
walk(root)
return out
JavaScript
function rangeKeys(root, lo, hi) {
const out = [];
function walk(node) {
if (node === null) return;
if (node.val > lo) walk(node.left);
if (node.val >= lo && node.val <= hi) out.push(node.val);
if (node.val < hi) walk(node.right);
}
walk(root);
return out;
}
Practice problems (4)
Which question needs order? Warm-up
A map stores integer keys. Which question can a balanced search tree answer in O(log n) but a hash map cannot answer quickly?
Range sum of a BST Warm-up
Given the root of a binary search tree and two integers lo and hi, return the sum of all keys k with lo ≤ k ≤ hi.
Floor and ceiling Standard
Given the root of a binary search tree and an integer target, return [floor, ceiling].
The floor is the largest key that is at most target. The ceiling is the smallest key that is at least target. Use -1 when there is no such key.
Count in range Standard
Given the root of a binary search tree and two integers lo and hi, return how many keys k satisfy lo ≤ k ≤ hi.
Skip every subtree that cannot hold a key in the range.
Next on the path: Binary heaps: array layout, sift up, sift down