Sub topic 14
Bit-Parallel Speedups with Myers' Algorithm
This chapter assumes you already know the Levenshtein recurrence, the dynamic programming table, the two-row implementation, and banded computation from earlier chapters. You should also be comfortable with Python's bitwise operators (&, |, ^, ~, <<) and with treating an integer as a vector of bits.
The two-row algorithm still does one min of three values for every cell, so it runs in O(mn) time. Gene Myers (1999) showed that a whole column of the table can be updated with about a dozen machine-word operations. If the shorter string fits in a 64-bit word, each column costs constant time, and the whole computation drops to O(n) word operations. The quadratic work is still there. It is packed 64 cells at a time into each instruction.
The Observation That Makes Packing Possible
Adjacent cells of a Levenshtein table differ by at most 1. Moving down a column, dp[i][j] - dp[i-1][j] is always -1, 0, or +1. The same holds moving across a row. This follows from the recurrence: a single insertion or deletion turns one prefix problem into its neighbor, so neighbors can never differ by more than one operation.
The consequence is that you never need to store the cell values themselves. You can store the first cell of the column, which is known, plus the vertical differences. Each difference has three possible values, so two bits per row are enough:
| Bit vector | Bit i is set when | Meaning |
|---|---|---|
| `Pv` | `dp[i][j] - dp[i-1][j] == +1` | positive vertical delta |
| `Mv` | `dp[i][j] - dp[i-1][j] == -1` | negative vertical delta |
| `Ph` | `dp[i][j] - dp[i][j-1] == +1` | positive horizontal delta |
| `Mh` | `dp[i][j] - dp[i][j-1] == -1` | negative horizontal delta |
A row where neither bit is set has delta 0. With m rows, Pv and Mv are two m-bit integers that describe the entire current column.
Precomputing Match Masks
Here a is the string packed into bits (called the pattern) and b is the string scanned one character at a time. For every character c, build a mask Peq[c] whose bit i is set when a[i] == c. When the algorithm reads b[j-1], the single integer Eq = Peq[b[j-1]] gives the match/mismatch result for the whole column at once. This replaces the cost = 0 if a[i-1] == b[j-1] else 1 test in the classic loop.
A dictionary handles any alphabet, including Unicode. A character that never occurs in a gets mask 0.
One Column Step
Each character of b turns the old column's vertical deltas into the new column's. The step runs in three stages:
- Compute where the new column's cells are fed by the diagonal or by a run of matches (
Xh,Xv). - Derive the horizontal deltas
PhandMhand use the top bit to update the running score, which is the value of the bottom cell. - Shift the horizontal deltas down one row and combine them with
Xvto get the newPvandMv.
The only unusual operation is the addition in Xh. Consider a cell where the diagonal predecessor is a match. That cell can pass a "free" zero-cost path down through later rows, but only while the old column keeps increasing (Pv bits set). Addition carries a 1 upward through a run of set bits, so (Eq & Pv) + Pv propagates each match through the run of +1 deltas below it. XOR with Pv then isolates the bits the carry flipped. A whole chain of dependent min decisions is resolved by the processor's carry logic in one instruction. Hyyrö's 2001 paper "Explaining and extending the bit-parallel approximate string matching algorithm of Myers" gives the full proof, cell by cell.
Global Edit Distance Implementation
This version computes the same value as levenshtein(a, b). The score starts at m, which is dp[m][0]. After each column, it moves by the horizontal delta of the bottom row.
import random
def myers_distance(a, b):
"""Levenshtein distance using Myers/Hyyro bit-parallel column updates."""
if len(a) > len(b):
a, b = b, a # pack the shorter string into bits
m = len(a)
if m == 0:
return len(b)
full = (1 << m) - 1 # m low bits set
top = 1 << (m - 1) # bit for the last row
peq = {}
for i, ch in enumerate(a):
peq[ch] = peq.get(ch, 0) | (1 << i)
pv, mv = full, 0 # column 0 is 0,1,2,...,m: every delta is +1
score = m
for ch in b:
eq = peq.get(ch, 0)
xv = eq | mv
xh = (((eq & pv) + pv) ^ pv) | eq
ph = mv | (~(xh | pv) & full)
mh = pv & xh
if ph & top:
score += 1
elif mh & top:
score -= 1
ph = ((ph << 1) | 1) & full # row 0 rises by 1 per column: shift in a +1
mh = (mh << 1) & full
pv = mh | (~(xv | ph) & full)
mv = ph & xv
return score
def levenshtein_two_rows(a, b):
if len(a) < len(b):
a, b = b, a
prev = list(range(len(b) + 1))
for i, ca in enumerate(a, 1):
curr = [i]
for j, cb in enumerate(b, 1):
curr.append(min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + (ca != cb)))
prev = curr
return prev[-1]
assert myers_distance("kitten", "sitting") == 3
assert myers_distance("", "abc") == 3
assert myers_distance("ab", "ba") == 2
random.seed(1)
for _ in range(2000):
x = "".join(random.choice("acgt") for _ in range(random.randint(0, 80)))
y = "".join(random.choice("acgt") for _ in range(random.randint(0, 80)))
assert myers_distance(x, y) == levenshtein_two_rows(x, y), (x, y)
print("all checks passed")The random cross-check against the plain two-row version matters. Bit-parallel code fails silently: one wrong shift or a missing mask still returns plausible numbers.
Approximate Search: The Original Use Case
Myers designed the algorithm for finding a short pattern anywhere inside a long text. The only change is the top row. In search mode, a match may start at any text position, so dp[0][j] = 0 for every j and the horizontal delta at row 0 is 0. You shift in a 0 instead of a 1, and you report every position where the score drops to the threshold k or below.
def myers_search(pattern, text, k):
"""Yield end indexes in text where pattern matches with at most k edits."""
m = len(pattern)
if m == 0:
yield from range(len(text))
return
full = (1 << m) - 1
top = 1 << (m - 1)
peq = {}
for i, ch in enumerate(pattern):
peq[ch] = peq.get(ch, 0) | (1 << i)
pv, mv, score = full, 0, m
for j, ch in enumerate(text):
eq = peq.get(ch, 0)
xv = eq | mv
xh = (((eq & pv) + pv) ^ pv) | eq
ph = mv | (~(xh | pv) & full)
mh = pv & xh
if ph & top:
score += 1
elif mh & top:
score -= 1
ph = (ph << 1) & full # row 0 is all zeros: shift in 0
mh = (mh << 1) & full
pv = mh | (~(xv | ph) & full)
mv = ph & xv
if score <= k:
yield j
assert list(myers_search("abc", "xxabcxx", 0)) == [4]
assert list(myers_search("abc", "xxabxx", 1)) == [3, 4]The second assertion reports two end positions. Ending at index 3 ("ab", with c deleted) and ending at index 4 ("abx", with c replaced by x) are both within one edit. Search results usually come in clusters like this. Real tools keep only the local minimum in each cluster, or run a traceback to find where each match starts.
Gotchas and Edge Cases
- Masking after
~. In Python,~xis negative and has infinitely many high bits set. Every~must be followed by& full. In C with unsigned 64-bit words, this happens automatically when m = 64. For smaller m you still need the mask, or you read the top bit at position m-1 as shown. - Carry overflow.
(eq & pv) + pvcan carry out past bit m-1. Bits above the column are harmless here because every later use is masked, but forgetting this makes C ports with m = 64 look wrong when they are correct. - Empty pattern.
top = 1 << -1raises an error, so handle m = 0 explicitly. - Long patterns. For m > w, split the column into ⌈m/w⌉ blocks and pass the horizontal carry (
Ph/Mhtop bit and the addition carry) from one block to the next. Hyyrö's blocked version also combines this with the threshold band from the previous chapter, so it processes only the blocks that can still reach a score of k or less. - Weighted costs. The algorithm depends on neighbors differing by exactly -1, 0, or +1. Custom operation costs break that, so this method covers only unit-cost Levenshtein and close relatives. Hyyrö published an OSA extension that adds a transposition term.
- No traceback. Like the two-row method, the algorithm keeps only the current column. To recover an edit script, you need to store columns or recompute a region.
When to Reach for It
| Situation | Best choice |
|---|---|
| Short strings (names, words) compared in bulk | Bit-parallel, m ≤ 64, one word per column |
| Long strings with a small threshold k | Banded DP, or blocked bit-parallel with banding |
| Non-unit or per-character costs | Classic DP |
| Need the actual edits | Full table or Hirschberg, possibly after a bit-parallel filter |
| Find a pattern anywhere in a text | Bit-parallel search mode |
A common pattern is a two-stage pipeline. The fast bit-parallel pass rejects candidates whose distance is above k. The slower table-based code then runs only on the survivors to produce alignments.
Exercise
In myers_distance, why does the global version shift a 1 into the low bit of Ph, while myers_search shifts in a 0?
Show answer
The shifted-in bit is the horizontal delta of row 0. For global distance, dp[0][j] = j, so row 0 rises by 1 in every column, which is a +1 delta. In search mode, dp[0][j] = 0 for all j because a match may start anywhere, so the delta is 0.
Exercise
You need the distance between 10,000-character DNA reads, and you only care whether it is at most 50. On a 64-bit machine, roughly how many words does a full column need, and what technique keeps the work low?
Show answer
A full column needs ceil(10000/64) = 157 words. Combine the blocked algorithm with the threshold band: only the blocks covering the diagonal band of width about 2k+1 = 101 rows (two or three words) need updating per column. That cuts the work from about 157 to about 3 word blocks per character.
Exercise
Explain why Myers' algorithm cannot directly compute a weighted edit distance where substitution costs 2 and insertion and deletion cost 1.
Show answer
The bit encoding assumes every vertical and horizontal delta is -1, 0, or +1, so two bits per cell can represent it. Different costs per operation make other differences possible (or different update rules for the same deltas), so the fixed Boolean formulas no longer give the correct minimum.