Sub topic 14
Bit-Parallel Speedups with Myers' Algorithm
This chapter assumes you know the DP table recurrence, the two-row version from earlier chapters, and Python's bitwise operators (&, |, ^, ~, <<). The goal here is to see how Myers' algorithm packs a whole table column into machine words. You don't need to derive every bit trick.
The Key Observation: Neighbors Differ by at Most One
In the Levenshtein table, two cells next to each other in the same column differ by -1, 0, or +1. The same holds for neighbors in the same row. So you don't need to store each cell's full value. Storing only the differences between neighbors is enough.
Myers (1999), in the form Hyyrö later adapted for plain edit distance, represents the vertical differences in one column with two bit vectors:
| Vector | Bit i is set when |
|---|---|
| `pv` (plus vertical) | `dp[i][j] - dp[i-1][j] == +1` |
| `mv` (minus vertical) | `dp[i][j] - dp[i-1][j] == -1` |
If neither bit is set, the difference is 0. ph and mh encode the horizontal differences in the same way. A precomputed table peq[c] has bit i set wherever a[i] == c.
One Column per Handful of Word Operations
Each character of b moves the computation one column to the right. With the pattern packed into a word, that update is a fixed set of AND, OR, XOR, shift, and one addition. The addition does the real work. Its carry chain moves "match" information down the column the way the min in the recurrence does, all bits at once.
The score starts at dp[m][0] = m. At each column it follows the bottom row using the horizontal difference stored in the top bit.
import random
def myers_distance(a, b):
m = len(a)
if m == 0:
return len(b)
peq = {}
for i, c in enumerate(a):
peq[c] = peq.get(c, 0) | (1 << i)
mask = (1 << m) - 1
high = 1 << (m - 1)
pv, mv, score = mask, 0, m
for c in b:
eq = peq.get(c, 0)
xv = eq | mv
xh = (((eq & pv) + pv) ^ pv) | eq
ph = mv | (~(xh | pv) & mask)
mh = pv & xh
if ph & high:
score += 1
elif mh & high:
score -= 1
ph = ((ph << 1) | 1) & mask # top row grows by 1 per column
mh = (mh << 1) & mask
pv = mh | (~(xv | ph) & mask)
mv = ph & xv
return score
def reference(a, b):
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
for _ in range(2000):
x = "".join(random.choices("abc", k=random.randint(0, 10)))
y = "".join(random.choices("abc", k=random.randint(0, 10)))
assert myers_distance(x, y) == reference(x, y)
print("ok")Cost
If m is at most the word size w (64 on most CPUs), each column costs O(1), so the whole run takes O(n) time. For longer patterns, split the column into ⌈m/w⌉ blocks and carry between them, which gives O(n·⌈m/w⌉). That is still quadratic in theory, but in practice it runs about 64 times faster. Python's integers have no size limit, so the code above works for any m, though each operation slows down as m grows.
Common Errors
- Unmasked
~. In Python,~xis negative and acts as an endless run of 1 bits. Always AND it withmask. - Wrong shift-in bit. For global distance, the top row is
dp[0][j] = j, sophgets a 1 shifted in. For substring search, where the top row is all zeros, you shift in 0. - Expecting traceback. Like the two-row method, this version keeps only the distance.
Exercise
Why does the algorithm need only two bit vectors per column instead of storing m+1 integers?
Show answer
Vertically adjacent cells differ by exactly -1, 0, or +1. One bit in pv and one bit in mv encode those three cases. The score at the bottom row is tracked separately, so you can rebuild any cell value from the differences.
Exercise
For a pattern of length 200 on a 64-bit machine, how many words does each column need, and what is the total running time for a text of length n?
Show answer
⌈200/64⌉ = 4 words per column, so about 4n word-operation groups, which is O(n·⌈m/w⌉).