Rank and Select on Bit Vectors
Almost every succinct data structure is built on one primitive: a bit vector with two queries,
- : the number of 1s in ;
- : the position of the -th 1.
( is , and is built the same way as .) With them, a bit vector becomes a navigable index: a sorted set of integers stored as a bitmap answers "how many elements are below " with rank and "the -th element" with select; succinct trees and the FM-index reduce their navigation to rank and select.
Theorem (Jacobson 1989 for rank; Clark 1996 and Munro 1996 for select). On a word-RAM with , a bit vector of bits can be augmented with additional bits so that rank and select take time.
The two-level directory for rank
Storing the answer for every would take bits. Store it only at a few places and compute the rest:
- Superblocks of bits. For each, store the absolute rank at its start: counters of bits, bits.
- Blocks of bits. For each, store the rank at its start relative to its superblock, a number below : counters of bits, bits.
- Within a block, the remaining count is a popcount of at most bits. Use a lookup table indexed by the block's bits and the prefix length: patterns times lengths, entries of bits, bits. (On a real machine, a
popcntinstruction replaces the table.)
So : three memory accesses, time, with extra bits.
RANK1(i)
1 s = floor(i / superblock size); k = floor(i / block size)
2 return SUPER[s] + BLOCK[k] + POPCOUNT(bits of block k before position i)Select is harder because the positions of the -th ones are not evenly spaced. Clark's construction splits the bit vector into pieces containing ones each; a piece that is long (more than bits) is sparse enough to store all its answers explicitly, and a short one is split again with a second level and finished by a table. Every level uses bits, and the query is . Many practical implementations instead binary-search the superblock counts, which costs time but no extra space.
A practical implementation
The program uses the parameters of practical libraries: superblocks of 512 bits with a full counter, and a 9-bit relative counter for each 64-bit word, which then needs a single popcount. Select binary-searches the superblock counts, scans at most 8 word counters, then clears the lowest ones of the final word. All answers are checked against prefix sums.
import bisect, random
class RankSelect:
"""Bit vector with a two-level rank directory: superblocks of 512 bits, words of 64 bits.
super_rank[s]: ones before superblock s (a full counter); word_rank[i]: ones before word i
inside its superblock (needs only 9 bits, since it is below 512)."""
W, SUPER = 64, 512
def __init__(self, bits):
self.n = len(bits)
self.words = [0] * ((self.n + 63) // 64)
for i, b in enumerate(bits):
if b: self.words[i >> 6] |= 1 << (i & 63)
per = self.SUPER // self.W # 8 words per superblock
self.super_rank, self.word_rank = [], []
total = 0
for i, w in enumerate(self.words):
if i % per == 0:
self.super_rank.append(total); inner = 0
self.word_rank.append(inner)
c = bin(w).count("1") # popcount: one word operation
inner += c; total += c
self.ones = total
def rank1(self, i): # number of 1s in positions [0, i)
q, r = i >> 6, i & 63
if q == len(self.words): return self.ones
return (self.super_rank[q >> 3] + self.word_rank[q]
+ bin(self.words[q] & ((1 << r) - 1)).count("1"))
def select1(self, k): # position of the k-th 1 (k >= 1)
s = bisect.bisect_left(self.super_rank, k) - 1 # binary search over superblocks
q = s * 8
while q + 1 < min(len(self.words), (s + 1) * 8) and self.super_rank[s] + self.word_rank[q + 1] < k:
q += 1 # at most 8 words to scan
k -= self.super_rank[s] + self.word_rank[q]
w = self.words[q]
for _ in range(k - 1): w &= w - 1 # drop the lowest k - 1 ones
return (q << 6) + ((w & -w).bit_length() - 1)
def extra_bits(self): # space of the directory, as stored compactly
return len(self.super_rank) * 64 + len(self.word_rank) * 9
rng = random.Random(1989)
n = 200000
bits = [1 if rng.random() < 0.3 else 0 for _ in range(n)]
rs = RankSelect(bits)
prefix = [0]
for b in bits: prefix.append(prefix[-1] + b)
positions = [i for i, b in enumerate(bits) if b]
for _ in range(3000):
i = rng.randrange(n + 1)
assert rs.rank1(i) == prefix[i]
k = rng.randrange(1, rs.ones + 1)
assert rs.select1(k) == positions[k - 1]
print(f"n = {n} bits, {rs.ones} ones; 3000 rank and 3000 select queries correct")
print(f"directory: {rs.extra_bits()} bits = {100 * rs.extra_bits() / n:.1f}% of n")
print("rank1(1000) =", rs.rank1(1000), " select1(300) =", rs.select1(300))n = 200000 bits, 59619 ones; 3000 rank and 3000 select queries correct
directory: 53149 bits = 26.6% of n
rank1(1000) = 300 select1(300) = 994
A quarter of is not "", though: with fixed block sizes the overhead is a constant fraction. The theoretical parameters give a vanishing fraction, but very slowly, as the next program shows by computing the three parts of the directory for growing .
import math
# Jacobson-style directory with the textbook parameters, as a fraction of n:
# superblocks of lg^2 n bits, each storing a lg n-bit absolute rank;
# blocks of (lg n)/2 bits, each storing a 2 lg lg n-bit rank relative to its superblock;
# a table of popcounts of every (lg n)/2-bit pattern and prefix length.
for e in [16, 20, 32, 48, 64]:
n, lg = 2 ** e, e
sup = n / lg ** 2 * lg
blk = n / (lg / 2) * 2 * math.log2(lg)
table = 2 ** (lg / 2) * (lg / 2) * math.log2(lg)
print(f"n = 2^{e}: superblocks {100 * sup / n:5.2f}% blocks {100 * blk / n:6.2f}% "
f"table {100 * table / n:8.5f}% total {100 * (sup + blk + table) / n:6.2f}% of n")n = 2^16: superblocks 6.25% blocks 100.00% table 12.50000% total 118.75% of n
n = 2^20: superblocks 5.00% blocks 86.44% table 4.22063% total 95.66% of n
n = 2^32: superblocks 3.12% blocks 62.50% table 0.12207% total 65.75% of n
n = 2^48: superblocks 2.08% blocks 46.54% table 0.00080% total 48.63% of n
n = 2^64: superblocks 1.56% blocks 37.50% table 0.00000% total 39.06% of n
Even at the textbook directory takes 39% of , worse than the practical 512/64 design. Asymptotically , practically a constant: real libraries pick block sizes by hand (common choices give 3% to 25% overhead) and use hardware popcount. Pătrașcu (2008) showed that the redundancy can be cut to bits with query time, and that is essentially optimal.
In C++
Words of 64 bits with std::popcount and std::countr_zero (C++20 <bit>), a 64-bit counter per 512-bit superblock and a 16-bit counter per word. The program checks select at every 1 of a 4-million-bit vector and rank on a stride.
#include <bit>
#include <cstdint>
#include <cstdio>
#include <random>
#include <vector>
// Rank/select directory: one 64-bit absolute count per 512-bit superblock, one 16-bit relative count per word.
class RankSelect {
std::vector<std::uint64_t> words;
std::vector<std::uint64_t> super_rank;
std::vector<std::uint16_t> word_rank;
std::uint64_t ones = 0;
public:
explicit RankSelect(const std::vector<std::uint64_t>& w) : words(w) {
std::uint16_t inner = 0;
for (std::size_t i = 0; i < words.size(); ++i) {
if (i % 8 == 0) { super_rank.push_back(ones); inner = 0; }
word_rank.push_back(inner);
int c = std::popcount(words[i]);
inner = static_cast<std::uint16_t>(inner + c);
ones += c;
}
}
std::uint64_t count() const { return ones; }
std::uint64_t rank1(std::uint64_t i) const { // ones in [0, i)
std::size_t q = i >> 6;
if (q == words.size()) return ones;
std::uint64_t below = (std::uint64_t{1} << (i & 63)) - 1;
return super_rank[q >> 3] + word_rank[q] + std::popcount(words[q] & below);
}
std::uint64_t select1(std::uint64_t k) const { // position of the k-th one, k >= 1
std::size_t lo = 0, hi = super_rank.size(); // last superblock with rank < k
while (hi - lo > 1) { std::size_t mid = (lo + hi) / 2; (super_rank[mid] < k ? lo : hi) = mid; }
std::size_t q = lo * 8;
while (q + 1 < words.size() && q + 1 < (lo + 1) * 8 && super_rank[lo] + word_rank[q + 1] < k) ++q;
k -= super_rank[lo] + word_rank[q];
std::uint64_t w = words[q];
for (std::uint64_t j = 1; j < k; ++j) w &= w - 1; // clear the lowest k - 1 ones
return (q << 6) + std::countr_zero(w);
}
};
int main() {
std::mt19937_64 rng(1989);
const std::size_t n = 1 << 22;
std::vector<std::uint64_t> w(n / 64);
for (auto& x : w) x = rng() & rng(); // density about 1/4
RankSelect rs(w);
int bad = 0;
std::uint64_t naive_rank = 0;
for (std::uint64_t i = 0, k = 0; i < n; ++i) { // check select at every one, rank on a stride
if (i % 4097 == 0) bad += rs.rank1(i) != naive_rank;
if ((w[i >> 6] >> (i & 63)) & 1) { ++naive_rank; ++k; bad += rs.select1(k) != i; }
}
std::printf("n = %zu bits, %llu ones, mismatches: %d\n", n, static_cast<unsigned long long>(rs.count()), bad);
std::printf("directory: %zu bits, %.1f%% of n\n", (n / 512) * 64 + (n / 64) * 16,
100.0 * ((n / 512) * 64 + (n / 64) * 16) / n);
}n = 4194304 bits, 1049745 ones, mismatches: 0
directory: 1572864 bits, 37.5% of n
Applications
| Use | How rank/select help |
|---|---|
| a sorted set as a bitmap | ; the -th element |
| sparse sets (Elias-Fano code) | the high bits of the sorted elements are written in unary in a bit vector of bits; select finds an element's high part in , giving bits for a set |
| variable-length records packed in an array | mark record starts with 1s: record starts at |
| succinct trees | parent, child and subtree size become rank/select on the balanced-parentheses or level-order bit sequence |
| wavelet trees, FM-index | rank on bit vectors at each level answers on a string of any alphabet (FM-index) |
The Elias-Fano row reaches within bits of the lower bound , which is why search engines store posting lists that way.
Test yourself
In the bit vector (positions 0 to 7, left to right), what are and ?
- 3 and 5
- 3 and 6
- 4 and 5
- 4 and 6
Why do the block counters in the two-level rank directory need only bits each?
- Blocks are short
- They store the rank relative to their superblock, which is less than the superblock size
- They store popcounts of one word
- They are compressed with Huffman codes
The practical directory in the program uses about 26% extra space. Why is that not a contradiction with the theorem?
- The theorem is wrong
- The theorem's parameters grow with ; with fixed block sizes the overhead is a constant fraction, and the theoretical overhead shrinks only very slowly
- Python integers are large
- Select needs more space