Sub topic 13
Stopping Early: Banded Computation with a Threshold
This chapter assumes you already know the full dynamic programming table, the two-row version, and why the plain algorithm costs O(mn) time. It shows how to make the computation much cheaper when you only care about small distances.
Why a Threshold Changes the Problem
Many uses of edit distance don't need the exact value. A spell checker only wants dictionary words within distance 2 of the typed word. A fuzzy search wants records within distance 3 of the query. In both cases, "the distance is 17" and "the distance is 40" mean the same thing: no match.
That turns the question into a decision: is d(a, b) <= k? If yes, return the distance. If no, return any value greater than k. This weaker requirement lets you skip most of the table.
The Key Lower Bound: Distance from the Diagonal
Cell dp[i][j] holds the distance between the first i characters of a and the first j characters of b. Two prefixes of different lengths need at least one insertion or deletion per character of length difference, so:
dp[i][j] >= |i - j|
Every edit path starts at (0, 0) and ends at (m, n), and the costs along a path never go down. If a path goes through any cell with |i - j| > k, its total cost is already more than k. When you only care about distances up to k, you can treat those cells as "too expensive" and never compute them.
The cells left over form a band around the main diagonal, at most 2k + 1 cells wide in each row.
Two Ways to Stop Early
The banded algorithm has two exits that save work.
- Length check before starting. The final cell has
|m - n|as a lower bound. If|m - n| > k, return immediately without touching the table. For dictionary search this test alone throws out many candidates. - Row-minimum check after each row. Every monotone path from
(0, 0)to(m, n)passes through at least one cell in every row. If every cell in rowialready exceedsk, no path can finish withink, so stop.
The second check is what makes a hopeless comparison cheap. Two unrelated words often blow past k after a few rows.
Implementation
The code below keeps two rows, as in the earlier chapter, but only writes the band. To keep the time at O(k · min(m, n)), it never clears a whole row. It resets only the two cells just outside the band that the next steps will read.
import random
def bounded_levenshtein(a, b, k):
"""Return the Levenshtein distance if it is <= k, otherwise k + 1."""
if len(a) < len(b):
a, b = b, a # keep the shorter string along the row
m, n = len(a), len(b)
if m - n > k:
return k + 1
cap = k + 1
prev = [min(j, cap) for j in range(n + 1)]
curr = [cap] * (n + 1)
for i in range(1, m + 1):
lo = max(1, i - k)
hi = min(n, i + k)
# Left neighbour of the band: real boundary value or "too far".
curr[lo - 1] = min(i, cap) if lo == 1 else cap
# Right neighbour: the next row will read it as prev[hi + 1].
if hi < n:
curr[hi + 1] = cap
row_min = curr[lo - 1]
ca = a[i - 1]
for j in range(lo, hi + 1):
v = min(prev[j] + 1,
curr[j - 1] + 1,
prev[j - 1] + (ca != b[j - 1]))
if v > cap:
v = cap
curr[j] = v
if v < row_min:
row_min = v
if row_min > k:
return cap
prev, curr = curr, prev
return prev[n]
def levenshtein(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 bounded_levenshtein("kitten", "sitting", 3) == 3
assert bounded_levenshtein("kitten", "sitting", 2) == 3 # means "more than 2"
assert bounded_levenshtein("", "abc", 5) == 3
assert bounded_levenshtein("abc", "abc", 0) == 0
# Randomized check against the full algorithm.
random.seed(1)
for _ in range(5000):
a = "".join(random.choice("abc") for _ in range(random.randint(0, 8)))
b = "".join(random.choice("abc") for _ in range(random.randint(0, 8)))
k = random.randint(0, 6)
full = levenshtein(a, b)
assert bounded_levenshtein(a, b, k) == min(full, k + 1), (a, b, k)
print("all checks passed")Three details are easy to get wrong.
- Stale cells. After
prev, curr = curr, prev, the arraycurrstill holds values from two rows back. The cell atlo - 1was inside that older band, so it holds a real but wrong number. If you don't reset it, the result can be too small. - Capping. Values are clamped to
k + 1. Without the clamp, numbers coming from "outside" cells grow pastcapand the row-minimum test still works, but the returned value is no longer consistentlyk + 1for "too far". - The final cell must be inside the band. It is, because the length check guarantees
n >= m - k.
Cost Compared with the Full Table
Each row computes at most 2k + 1 cells, and there are m rows, with the shorter string along the row.
| Method | Time | Extra memory | Exact distance? |
|---|---|---|---|
| Full table | O(mn) | O(mn) | Yes, plus traceback |
| Two rows | O(mn) | O(min(m, n)) | Yes |
| Banded, threshold k | O(k · max(m, n)) | O(min(m, n)) | Only if it is <= k |
| Banded with doubling | O(d · max(m, n)) | O(min(m, n)) | Yes |
For k = 2 and 10,000-character strings, the band computes about 50,000 cells instead of 100 million. The memory above still uses full-length rows. You can store only the 2k + 1 band cells by indexing on j - i + k, which brings memory down to O(k) at the price of trickier index arithmetic.
Getting the Exact Distance Without Knowing k: Doubling
If you want the exact distance d but expect it to be small, run the bounded version with k = 1, 2, 4, 8, ... until it succeeds. The final run costs O(d · n), and the earlier runs form a geometric series with the same total, so the whole thing is O(d · n). This idea goes back to Ukkonen (1985).
def levenshtein_doubling(a, b):
k = 1
while True:
d = bounded_levenshtein(a, b, k)
if d <= k:
return d
k *= 2
assert levenshtein_doubling("kitten", "sitting") == 3
assert levenshtein_doubling("flaw", "lawn") == 2
assert levenshtein_doubling("same", "same") == 0When d approaches the string length, doubling costs a constant factor more than the plain algorithm. Use it when small distances are the common case.
A Tighter Band for Unequal Lengths
The bound |i - j| ignores where the path still has to go. From cell (i, j), the remaining suffixes have lengths m - i and n - j, so at least |(m - i) - (n - j)| more edits are needed. A cell is worth computing only if
|i - j| + |(m - i) - (n - j)| <= k
When m - n = k, this bound shrinks the band to a single diagonal. Library implementations such as RapidFuzz use bounds like this. The symmetric band in the code above is correct, just a little wider than it needs to be.
Gotchas and Decision Criteria
- Traceback. The banded algorithm here keeps two rows, so it cannot recover the edit script. If you need the script, store the full band (O(k · n) memory) and trace back inside it. All cells on an optimal path lie in the band when
d <= k. - Weighted costs. The lower bound becomes
|i - j| · min(insert cost, delete cost). With very cheap insertions, the band has to grow. - Transpositions. Optimal string alignment reads
dp[i-2][j-2], which stays on the same diagonal, so the same band works. - When not to bother. If thresholds are large compared with string length, say
k > n / 4, the band is most of the table and the bookkeeping costs more than it saves.
Exercise
For a = "abcdefgh" and b = "abcdefghxyz" with k = 2, how many table cells does bounded_levenshtein compute, and why?
Show answer
Zero. After the swap, m = 11 and n = 8, so m - n = 3 > 2. The length check returns k + 1 = 3 before any cell is filled.
Exercise
Suppose you remove the line that resets curr[lo - 1] when lo > 1. Explain what can go wrong and give the direction of the error.
Show answer
After the row swap, curr[lo - 1] holds a value from row i - 2, where that column was inside the band. When computing curr[lo], the term curr[lo - 1] + 1 can then use this stale value, which is often smaller than the true "too far" value. The result can come out too small, so the function may report a match that does not exist.
Exercise
Your fuzzy search usually finds matches at distance 0 or 1, but you need exact distances, and strings are about 5,000 characters long. Compare the cost of the two-row algorithm with doubling for d = 1.
Show answer
Two rows always compute about 5,000 × 5,000 = 25 million cells. Doubling with d = 1 succeeds on the first call with k = 1, computing about 3 × 5,000 = 15,000 cells. That is over 1,000 times fewer cells, so doubling is the better choice.