Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

Bit-Parallel Algorithms

Bitsets, word-level parallelism, Shift-And matching and the Four Russians.

A 64-bit AND is 64 Boolean ANDs for the price of one instruction. Arrange an algorithm so that its innermost loop combines whole rows of bits, and it runs dozens of times faster on the same machine. This word-level parallelism is behind the bitset subset-sum DP, the agrep text searcher, Myers's edit-distance algorithm, and the "Four Russians" trick for Boolean matrices, the start of a line of work that reached a research milestone in 2024.

What you’ll learn

  • State the word-RAM model and explain why a bitset turns nn Boolean operations into ⌈n/w⌉\lceil n/w\rceil word operations.
  • Speed up subset sum to O(nt/w)O(nt/w) and graph reachability by a factor ww with bitsets, with correctness invariants.
  • Derive the Shift-And recurrence for exact matching, and explain how Wu–Manber and Myers extend bit-parallelism to errors and edit distance.
  • Analyze the Four Russians algorithm for Boolean matrix multiplication, O(n3/(wlog⁡n))O(n^3/(w\log n)), and place it in the history of combinatorial algorithms up to 2024.

The word RAM and the bitset

The word RAM stores data in words of ww bits, with w≥log⁡2nw\ge\log_2 n so that a word can hold an index, and charges one step for each AND, OR, XOR, NOT, shift, addition or comparison of whole words. A bitset of nn bits occupies ⌈n/w⌉\lceil n/w\rceil words, so a bulk AND, OR, XOR or shift costs O(n/w)O(n/w), and so does counting its ones, since modern processors count a word's set bits in one instruction. That is word-level parallelism: a speedup of w=64w=64 with ordinary registers, and more with 256- or 512-bit vector registers.

The classic example is subset sum: can some subset of nn positive integers reach every target up to tt? Keep the set of reachable sums as one bitset RR, bit ss meaning "sum ss is reachable".

DerivationThe shift-or recurrence
  1. R0={0}=1R_0=\{0\}=1

    Let RiR_i be the set of sums of subsets of the first ii items, as a bitset over 0..t0..t. Initially only the empty subset exists:

  2. Ri=Ri−1 ∣ (Ri−1≪ai)(truncated to bits 0..t)R_i=R_{i-1}\ \big|\ \big(R_{i-1}\ll a_i\big)\quad\text{(truncated to bits }0..t)

    A subset of the first ii items either skips item ii or uses it, which adds aia_i to every sum. Shifting left by aia_i adds aia_i to every element of the set at once:

  3. T(n,t)=O(n ⌈t/w⌉)T(n,t)=O\big(n\,\lceil t/w\rceil\big)

    Each item costs O(t/w)O(t/w) word operations instead of O(t)O(t) bit operations, so all nn items cost O(nt/w)O(nt/w). It is still pseudo-polynomial: the running time grows with the value tt, not with its number of bits.

cpp
#include <bitset>
#include <cstdio>
#include <vector>

int main() {
    const int MAXT = 100000;                       // largest target, fixed at compile time
    std::vector<int> items = {3, 5, 7};
    std::bitset<MAXT + 1> reach;
    reach[0] = 1;                                  // the empty subset
    for (int a : items) reach |= reach << a;       // about MAXT / 64 word operations per item
    for (int s = 0; s <= 15; s++)
        if (reach[s]) std::printf("%d ", s);       // 0 3 5 7 8 10 12 15
}

std::bitset needs its size at compile time. In Python, a plain integer works as a bitset: reach |= (reach << a) & full, with full = (1 << (t + 1)) - 1, runs its shifts and ORs in C over machine words.

ProblemPlainWith bitsetsInner operation
Subset sum up to ttO(nt)O(nt)O(nt/w)O(nt/w)R |= R << a
Transitive closure (Warshall)O(n3)O(n^3)O(n3/w)O(n^3/w)if ii reaches kk: rowi∣=rowk\text{row}_i \mathrel{|}= \text{row}_k
Reachability from every vertex of a DAGO(nm)O(nm)O(nm/w)O(nm/w)reach(v)={v}∪⋃v→ureach(u)\text{reach}(v)=\{v\}\cup\bigcup_{v\to u}\text{reach}(u)
Counting trianglesO(mn)O(mn)O(mn/w)O(mn/w)popcount of N(u)∩N(v)N(u)\cap N(v) for each edge
Gaussian elimination over GF(2)\mathrm{GF}(2)O(n3)O(n^3)O(n3/w)O(n^3/w)XOR of rows
In each case the innermost loop over bits becomes a loop over words. For reachability, process the DAG in reverse topological order; for triangles, each triangle is counted once per edge, three times in all.

Shift-And: one shift per text character

Bit-parallelism also simulates automata. To find a pattern pp of length mm in a text tt, keep a bit vector DD with one bit per pattern prefix: after reading t[i]t[i], bit jj of DD is 1 exactly when p[0..j]p[0..j] occurs in the text ending at position ii. Precompute a mask B[c]B[c] for each character cc, with bit jj set exactly when p[j]=cp[j]=c.

DerivationThe Shift-And recurrence (Baeza-Yates & Gonnet, 1992)
  1. Di[j]=(j=0 ∨ Di−1[j−1]) ∧ (p[j]=t[i])D_i[j]=\big(j=0\ \lor\ D_{i-1}[j-1]\big)\ \land\ \big(p[j]=t[i]\big)

    The prefix p[0..j]p[0..j] ends at ii exactly when p[0..j−1]p[0..j-1] ends at i−1i-1 (for j=0j=0: always) and p[j]=t[i]p[j]=t[i]:

  2. Di=((Di−1≪1)∣1) & B[t[i]]D_i=\big((D_{i-1}\ll1)\mid1\big)\ \&\ B[t[i]]

    All mm bits at once: shift to move every partial match one position along, OR in 1 to start a new match, and AND with the character's mask:

  3. match at i−m+1  ⟺  Di[m−1]=1\text{match at } i-m+1\iff D_i[m-1]=1

    A full occurrence ends at ii when bit m−1m-1 is set. Each character costs O(⌈m/w⌉)O(\lceil m/w\rceil) word operations, so the scan takes O(n⌈m/w⌉)O(n\lceil m/w\rceil) time after O(∣Σ∣+m)O(\abs{\Sigma}+m) preprocessing: linear in nn when the pattern fits in a word.

python
def shift_and(text, pat):
    m = len(pat)
    B = {}
    for j, ch in enumerate(pat):       # B[c]: bit j set iff pat[j] == c
        B[ch] = B.get(ch, 0) | 1 << j
    D, hits = 0, []
    for i, ch in enumerate(text):
        D = ((D << 1) | 1) & B.get(ch, 0)
        if (D >> (m - 1)) & 1:         # pat ends at text position i
            hits.append(i - m + 1)
    return hits

print(shift_and("abaababaab", "abab"))   # [3]

For the pattern abab, B[a]=01012B[\mathtt a]=0101_2 and B[b]=10102B[\mathtt b]=1010_2. The state reads 0001,0010,0101,0001,0010,0101,10100001,0010,0101,0001,0010,0101,1010 over the first seven characters; bit 3 is set after position 6, so the match starts at 3.

Errors. Wu and Manber (1992), in the agrep tool, keep k+1k+1 vectors R0,…,RkR^0,\dots,R^k, where RdR^d marks the prefixes that match with at most dd edits. Each edit type is one more shift or OR of the previous vectors:

R′ d=(((Rd≪1)∣1) & B[c]) ∣ Rd−1 ∣ ((Rd−1∣R′ d−1)≪1) ∣ 1,R'^{\,d}=\big(((R^d\ll1)\mid1)\ \&\ B[c]\big)\ \mid\ R^{d-1}\ \mid\ \big((R^{d-1}\mid R'^{\,d-1})\ll1\big)\ \mid\ 1,

where the terms are a match, an inserted text character, a substitution and a deleted pattern character (the final 1: a one-character prefix is always within one edit). Initially Rd=2d−1R^d=2^d-1. That is O(kn⌈m/w⌉)O(kn\lceil m/w\rceil) time.

Edit distance. Myers (1999) went further: adjacent cells of the edit-distance table differ by −1-1, 00 or +1+1, so a whole column fits in two bit vectors, and a constant number of word operations advances it by one text character. Approximate matching then takes O(n⌈m/w⌉)O(n\lceil m/w\rceil) time for any number of errors (see Edit Distance & Its Limits).

Check your understanding

In Shift-And with pattern pp, what does it mean when bit jj of DD is 1 after reading text position ii?

  1. p[j]=t[i]p[j]=t[i]
  2. The prefix p[0..j]p[0..j] occurs in the text ending at position ii
  3. The pattern occurs starting at position jj
  4. At least jj characters of the pattern have matched somewhere in the text so far
Show the answer

B. The prefix p[0..j]p[0..j] occurs in the text ending at position ii

DD tracks every partial match at once: bit jj says the last j+1j+1 text characters equal p[0..j]p[0..j]. The mask B[t[i]]B[t[i]] checks only the newest character; the shift carries the older ones.

The Four Russians: precomputed tables of rows

Boolean matrix multiplication (BMM) computes C[i][j]=⋁k(A[i][k]∧B[k][j])C[i][j]=\bigvee_k\big(A[i][k]\wedge B[k][j]\big). With bitset rows, row ii of CC is the OR of the rows kk of BB for which A[i][k]=1A[i][k]=1: nn row-ORs of n/wn/w words for each of nn rows, O(n3/w)O(n^3/w).

Arlazarov, Dinic, Kronrod and Faradzev (1970), the "Four Russians", saved one more logarithmic factor with a table. Cut the index range of kk into blocks of tt. Within a block, the row of AA selects one of only 2t2^t subsets of the block's tt rows of BB, so precompute the OR of every such subset once, and replace up to tt row-ORs by one lookup.

python
def bmm_four_russians(A, Brows, n, t):        # A: 0/1 lists; Brows[k]: row k of B as an int bitset
    C = [0] * n
    for start in range(0, n, t):              # a block of t columns of A (rows of B)
        blk = Brows[start:start + t]
        table = [0] * (1 << len(blk))         # table[s] = OR of the block rows selected by s
        for s in range(1, 1 << len(blk)):
            low = (s & -s).bit_length() - 1
            table[s] = table[s & (s - 1)] | blk[low]   # one OR per entry, from a smaller entry
        for i in range(n):
            key = 0
            for b in range(len(blk)):
                if A[i][start + b]:
                    key |= 1 << b
            C[i] |= table[key]                # one lookup replaces up to t row ORs
    return C

Each table entry costs one OR of n/wn/w words, built from the entry without its lowest bit. In practice the key is read directly from AA's bit-packed row, at no extra cost.

DerivationThe cost, with t = log₂ n
  1. T(n)=nt(2t⋅nw+n⋅nw)T(n)=\frac{n}{t}\Big(2^t\cdot\frac nw+n\cdot\frac nw\Big)

    There are n/tn/t blocks. Each builds a table of 2t2^t rows of n/wn/w words, then performs one lookup-and-OR for each of the nn rows of CC:

  2. T(n)=nlog⁡2n⋅2n2w=O ⁣(n3wlog⁡n)T(n)=\frac{n}{\log_2 n}\cdot\frac{2n^2}{w}=O\!\left(\frac{n^3}{w\log n}\right)

    Choosing t=log⁡2nt=\log_2 n makes 2t=n2^t=n, so the two terms balance:

  3. T(n)=O ⁣(n3log⁡2n)for w=Θ(log⁡n)T(n)=O\!\left(\frac{n^3}{\log^2 n}\right)\quad\text{for } w=\Theta(\log n)

    With w=Θ(log⁡n)w=\Theta(\log n) this is the familiar O(n3/log⁡2n)O(n^3/\log^2 n). Transitive closure has the same complexity as BMM up to constant factors (Fischer & Meyer, 1971; Munro, 1971), so it inherits the speedup; fittingly, the 1970 paper was about transitive closure.

Combinatorial algorithms and the frontier

Algebraic algorithms multiply Boolean matrices as integer matrices, in O(nω)O(n^\omega) time with ω<2.371339\omega<2.371339 as of 2025, but they rely on subtraction and huge hidden constants. Combinatorial algorithms, loosely those that avoid such algebra, like the Four Russians, have a story of their own:

YearCombinatorial BMMTime
1970Four Russians (Arlazarov, Dinic, Kronrod & Faradzev)O(n3/log⁡2n)O(n^3/\log^2 n)
2009Bansal & Williams, via regularity lemmasO~(n3/log⁡2.25n)\tilde O(n^3/\log^{2.25}n)
2015ChanO~(n3/log⁡3n)\tilde O(n^3/\log^3 n)
2015YuO~(n3/log⁡4n)\tilde O(n^3/\log^4 n)
2024Abboud, Fischer, Kelley, Lovett & Mekan3/2Ω((log⁡n)1/7)n^3/2^{\Omega((\log n)^{1/7})}
Bounds with w=Θ(log⁡n)w=\Theta(\log n); O~\tilde O hides factors polynomial in log⁡log⁡n\log\log n. The 2024 algorithm, built on a new regularity decomposition for Boolean matrices, is the first to beat cubic time by more than any polylogarithmic factor.

Key takeaways

  • On the word RAM, a bitset performs ww Boolean operations per instruction: subset sum becomes R∣=R≪aR\mathrel{|}=R\ll a in O(nt/w)O(nt/w), and closure, reachability, triangles and GF(2)\mathrm{GF}(2) elimination all gain a factor ww.
  • Shift-And keeps one bit per pattern prefix and updates all of them with D←((D≪1)∣1)&B[c]D\leftarrow((D\ll1)\mid1)\mathbin{\&}B[c], so exact matching costs O(n⌈m/w⌉)O(n\lceil m/w\rceil); Wu–Manber adds errors and Myers computes edit distance the same way.
  • The Four Russians precompute the OR of every subset of t≈log⁡nt\approx\log n rows, so Boolean matrix multiplication and transitive closure take O(n3/(wlog⁡n))O(n^3/(w\log n)).
  • Combinatorial BMM improved by polylogarithmic factors until 2024, when it first beat every polylogarithm; a truly subcubic combinatorial algorithm remains an open question that much of fine-grained complexity leans on.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A bitset subset-sum DP over n=1000n=1000 items and targets up to t=106t=10^6, with 64-bit words, performs about how many word operations?

  1. About 1.6×1071.6\times10^7
  2. About 10910^9
  3. About 2×1042\times10^4
  4. About 101210^{12}
Show the answer

A. About 1.6×1071.6\times10^7

n⋅t/w=1000⋅106/64≈1.6×107n\cdot t/w=1000\cdot10^6/64\approx1.6\times10^7 word operations, a fraction of a second. The plain DP needs nt=109nt=10^9 bit operations.

Question 2

What is the core idea of the Four Russians algorithm for Boolean matrix multiplication?

  1. Split each matrix into four quadrants and recurse, as in Strassen's algorithm
  2. For each block of t≈log⁡nt\approx\log n rows of BB, precompute the OR of all 2t2^t subsets of those rows, so one table lookup replaces up to tt row operations
  3. Multiply the matrices over the integers and round the result
  4. Sort the rows of AA so that equal rows are computed once
Show the answer

B. For each block of t≈log⁡nt\approx\log n rows of BB, precompute the OR of all 2t2^t subsets of those rows, so one table lookup replaces up to tt row operations

A row of AA restricted to a block can only select one of 2t2^t subsets of the block's rows. Precomputing all of them costs 2t⋅n/w2^t\cdot n/w per block, which with t=log⁡2nt=\log_2 n balances the lookups and gives O(n3/(wlog⁡n))O(n^3/(w\log n)) overall.

Question 3

Which statement about combinatorial Boolean matrix multiplication is correct as of 2025?

  1. No algorithm beats n3n^3 by more than a constant factor
  2. An O(n2.9)O(n^{2.9}) combinatorial algorithm is known
  3. The best known algorithm, from 2024, beats n3n^3 by a factor 2Ω((log⁡n)1/7)2^{\Omega((\log n)^{1/7})}, more than any polylogarithm, but no O(n3−ε)O(n^{3-\varepsilon}) combinatorial algorithm is known
  4. It is proved that no combinatorial algorithm can beat n3/log⁡4nn^3/\log^4 n
Show the answer

C. The best known algorithm, from 2024, beats n3n^3 by a factor 2Ω((log⁡n)1/7)2^{\Omega((\log n)^{1/7})}, more than any polylogarithm, but no O(n3−ε)O(n^{3-\varepsilon}) combinatorial algorithm is known

Abboud, Fischer, Kelley, Lovett and Meka (2024) broke the polylogarithmic barrier, yet 2Ω((log⁡n)1/7)2^{\Omega((\log n)^{1/7})} is still smaller than any nεn^\varepsilon. Whether a truly subcubic combinatorial algorithm exists is open.

Further reading

  • V. L. Arlazarov, E. A. Dinic, M. A. Kronrod & I. A. Faradzev, "On economical construction of the transitive closure of an oriented graph," Soviet Mathematics Doklady 11 (1970), 1209–1210.
  • R. Baeza-Yates & G. H. Gonnet, "A new approach to text searching," Communications of the ACM 35(10) (1992), 74–82.
  • S. Wu & U. Manber, "Fast text searching: allowing errors," Communications of the ACM 35(10) (1992), 83–91.
  • G. Myers, "A fast bit-vector algorithm for approximate string matching based on dynamic programming," Journal of the ACM 46(3) (1999), 395–415.
  • A. Abboud, N. Fischer, Z. Kelley, S. Lovett & R. Meka, "New graph decompositions and combinatorial Boolean matrix multiplication algorithms," Proceedings of STOC (2024), 935–943.