Data Structures19 sections · 729 units
Open in Course

Efficient Rank with Prefix Sums

O(1) rank queries

Precompute prefix sums for each bitvector:

function preprocess(bitvector)
    prefix := array of size length + 1
    prefix[0] := 0
    for i from 0 to length - 1
        prefix[i + 1] := prefix[i] + bitvector[i]
    return prefix

function rank1(prefix, i)
    return prefix[i]

function rank0(prefix, i)
    return i - prefix[i]

prefix[i]\text{prefix}[i] stores the count of 1s in the first ii positions.

Time: O(n)O(n) preprocessing per bitvector, O(1)O(1) per rank query.

Space: O(n)O(n) extra per bitvector.