How bitap matches a pattern with word shifts

Short answer: Bitap, or the Shift-Or algorithm, matches a pattern by keeping a bitset of the pattern prefixes that match the text so far. Each text character shifts the set and masks it with the character’s precomputed bit mask. A match is the bit at the pattern’s last position. The classic form assumes the pattern fits in a machine word, so a scan is O(n) word operations after O(m · σ) preprocessing. Wu-Manber extends the same bits to allow a small number of errors.


What the problem actually asks

KMP stores its automaton in a failure table and follows links. If the pattern is no longer than a word, the set of active prefixes is a word, and the transition is a shift and a bitwise OR or AND. The Shift-Or convention keeps a 0 bit for an active state so that the shift-in of a new active prefix uses a single OR with a mask that has zeros where the character is allowed.

The same bits answer a different question when an extra row of bits is kept for each error count. That is approximate bitap: an insertion, deletion, or substitution moves the search into the next error row. The pattern length is still bounded by the word size, or by a few words if the implementation uses multi-word arithmetic.


What the algorithm guarantees

Exact Shift-Or scans the text in O(n) word operations for m ≤ word size, after building a mask for each alphabet character in O(σ + m). Extra memory is the masks. Every match is detected when the high bit that represents a full pattern becomes active. Overlapping matches fall out of the same scan, because the bitset is not reset after a hit.

Wu-Manber with at most k errors uses k+1 bit words and still scans in O(k · n) word operations for a pattern that fits in one word. It computes edit distance only up to k and only for the pattern against windows of the text, not the full Levenshtein table between two long strings. A pattern longer than a word needs either multi-word bits or a different automaton.


The working steps

  1. For each alphabet character, build a mask of m bits. In the Shift-Or form, bit j is 0 when pattern[j] equals that character, and 1 otherwise.
  2. Set the state to all ones. A 0 bit will mean a live prefix.
  3. For each text character, shift the state left by one, set the new low bit to 0, and OR the state with the mask of the character.
  4. If the bit that represents position m−1 is 0, the pattern matches ending at this text index.
  5. For k errors, keep k+1 states. The transition for error row e combines the exact shift of row e with insertions, deletions, and substitutions drawn from row e−1, using shifts and ORs.

The linear scan is a word-RAM bound for a short pattern. It does not replace KMP for a pattern of thousands of characters unless the bits are multi-word and the cost is stated honestly. It is not a general edit-distance table. Levenshtein between two arbitrary strings is the quadratic DP. Bitap is pattern search, exact or with a small error budget.


Approaches that look simpler and fail

Approach Why it fails when the pattern is longer than the bit word
Pack m > 64 into one machine word The high bits fall off the shift. Matches past the word width are lost. Use multi-word arithmetic or a different algorithm.
Treat a 0 in an unrelated bit as a full match Only the bit at position m−1 means the entire pattern matched. Lower bits are proper prefixes.
Use the k-error transition and report it as full Levenshtein distance The rows stop at k. A distance above k is indistinguishable from “more than k” and is not a number.
Reset the state after every hit Overlapping matches need the prefixes that remain live. Resetting drops a match that started inside the previous one.

Long exact patterns belong to KMP, Boyer-Moore, or a suffix array. Full edit distance belongs to the Levenshtein DP. Bitap is the word-parallel automaton for a short pattern, with Wu-Manber as its small-k extension.


A working example

This Python fragment keeps a bit for each matched prefix. A 0 bit means the prefix is still live, which matches the Shift-Or orientation. The pattern cat occurs in a cat at index 2.

def bitap(text, pat):
    if not pat or len(pat) > 63:
        return -1
    mask = [~0] * 128
    for i, ch in enumerate(pat):
        mask[ord(ch)] &= ~(1 << i)
    state = ~1
    for i, ch in enumerate(text):
        state |= mask[ord(ch)]
        state <<= 1
        if (state & (1 << len(pat))) == 0:
            return i - len(pat) + 1
    return -1

assert bitap("a cat", "cat") == 2
print(bitap("a cat", "cat"))

Where it is used

agrep uses the bitap (shift-or) algorithm for approximate match of a short pattern: each bit of a word is one state of the automaton. A long pattern does not fit in a machine word and falls back to another matcher. Exact match of a long literal is Boyer-Moore or Aho-Corasick.


When you can drop this algorithm

Drop bitap when the pattern is long. The word-sized assumption is the algorithm. Keep it for short patterns, especially when a small error budget must be scanned in one pass over a large text.


Why this stays published

We publish this so a search for bitap returns the shift-and-mask state and the word-size limit that bounds the pattern. Bitap matches a short pattern in linear time by shifting a bitset of live prefixes and masking it with the current character, and Wu-Manber adds a row of bits per allowed error.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *