TExcelTAD
Home › Advanced & Succinct Data Structures › Rank and Select on Bit Vectors

Rank and Select on Bit Vectors

Almost every succinct data structure is built on one primitive: a bit vector b[0..n−1]b[0..n-1] with two queries,

  • rank⁡1(i)\operatorname{rank}_1(i): the number of 1s in b[0..i−1]b[0..i-1];
  • select⁡1(k)\operatorname{select}_1(k): the position of the kk-th 1.

(rank⁡0\operatorname{rank}_0 is i−rank⁡1(i)i - \operatorname{rank}_1(i), and select⁡0\operatorname{select}_0 is built the same way as select⁡1\operatorname{select}_1.) With them, a bit vector becomes a navigable index: a sorted set of integers stored as a bitmap answers "how many elements are below xx" with rank and "the kk-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 w=Θ(lg⁡n)w = \Theta(\lg n), a bit vector of nn bits can be augmented with o(n)o(n) additional bits so that rank and select take O(1)O(1) time.

The two-level directory for rank

Storing the answer for every ii would take nlg⁡nn \lg n bits. Store it only at a few places and compute the rest:

  1. Superblocks of s=lg⁡2ns = \lg^2 n bits. For each, store the absolute rank at its start: nlg⁡2n\frac{n}{\lg^2 n} counters of lg⁡n\lg n bits, O(nlg⁡n)=o(n)O(\frac{n}{\lg n}) = o(n) bits.
  2. Blocks of 12lg⁡n\frac{1}{2}\lg n bits. For each, store the rank at its start relative to its superblock, a number below lg⁡2n\lg^2 n: n12lg⁡n\frac{n}{\frac12 \lg n} counters of 2lg⁡lg⁡n2\lg \lg n bits, O(nlg⁡lg⁡nlg⁡n)=o(n)O(\frac{n \lg \lg n}{\lg n}) = o(n) bits.
  3. Within a block, the remaining count is a popcount of at most 12lg⁡n\frac12 \lg n bits. Use a lookup table indexed by the block's bits and the prefix length: 212lg⁡n=n2^{\frac12 \lg n} = \sqrt{n} patterns times 12lg⁡n\frac12 \lg n lengths, entries of lg⁡lg⁡n\lg \lg n bits, O(nlg⁡nlg⁡lg⁡n)=o(n)O(\sqrt{n} \lg n \lg \lg n) = o(n) bits. (On a real machine, a popcnt instruction replaces the table.)

So rank⁡1(i)=superblock count+block count+table lookup\operatorname{rank}_1(i) = \text{superblock count} + \text{block count} + \text{table lookup}: three memory accesses, O(1)O(1) time, with o(n)o(n) extra bits.

text
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 kk-th ones are not evenly spaced. Clark's construction splits the bit vector into pieces containing lg⁡2n\lg^2 n ones each; a piece that is long (more than lg⁡4n\lg^4 n 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 o(n)o(n) bits, and the query is O(1)O(1). Many practical implementations instead binary-search the superblock counts, which costs O(lg⁡n)O(\lg n) 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.

python · try it yourself
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 nn is not "o(n)o(n)", 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 nn.

python · try it yourself
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 n=264n = 2^{64} the textbook directory takes 39% of nn, worse than the practical 512/64 design. Asymptotically o(n)o(n), 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 n/(lg⁡n/t)t+O~(n3/4)n / (\lg n / t)^t + \tilde{O}(n^{3/4}) bits with O(t)O(t) 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.

cpp · try it yourself
#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 S⊆{0..U−1}S \subseteq \{0..U-1\} as a bitmap ∣S∩[0,x)∣=rank⁡1(x)\lvert S \cap [0, x) \rvert = \operatorname{rank}_1(x); the kk-th element =select⁡1(k)= \operatorname{select}_1(k)
sparse sets (Elias-Fano code) the high bits of the sorted elements are written in unary in a bit vector of 2n2n bits; select finds an element's high part in O(1)O(1), giving nlg⁡Un+2n+o(n)n \lg \frac{U}{n} + 2n + o(n) bits for a set
variable-length records packed in an array mark record starts with 1s: record kk starts at select⁡1(k)\operatorname{select}_1(k)
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 rank⁡c\operatorname{rank}_c on a string of any alphabet (FM-index)

The Elias-Fano row reaches within 2n2n bits of the lower bound lg⁡(Un)≈nlg⁡Un+1.44n\lg \binom{U}{n} \approx n \lg \frac{U}{n} + 1.44 n, which is why search engines store posting lists that way.

Test yourself

In the bit vector 1011 01101011\,0110 (positions 0 to 7, left to right), what are rank⁡1(5)\operatorname{rank}_1(5) and select⁡1(4)\operatorname{select}_1(4)?

  1. 3 and 5
  2. 3 and 6
  3. 4 and 5
  4. 4 and 6

Why do the block counters in the two-level rank directory need only O(lg⁡lg⁡n)O(\lg \lg n) bits each?

  1. Blocks are short
  2. They store the rank relative to their superblock, which is less than the superblock size lg⁡2n\lg^2 n
  3. They store popcounts of one word
  4. 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 o(n)o(n) theorem?

  1. The theorem is wrong
  2. The theorem's parameters grow with nn; with fixed block sizes the overhead is a constant fraction, and the theoretical overhead shrinks only very slowly
  3. Python integers are large
  4. Select needs more space