Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

Edit Distance & Its Limits

Alignment, bit-parallel speedups and the SETH lower bound.

The Wagner–Fischer table computes the edit distance of two strings of length nn in O(n2)O(n^2) time, and in half a century nobody has found an algorithm that is polynomially faster. Since 2015 there is a conditional explanation: a strongly subquadratic algorithm would refute the Strong Exponential Time Hypothesis. This lesson covers what can be done (fast algorithms when the distance is small, word-level parallelism, near-linear approximation) and why the barrier stands.

What you’ll learn

  • Prove the structural facts behind fast edit-distance algorithms: the band lemma and the 0/1 steps along diagonals.
  • Compute the edit distance in O(nk)O(nk) time when it is at most kk, in O((n+m)D)O((n + m)D) by diagonal transitions, and in O(n+k2)O(n + k^2) with constant-time longest common extensions.
  • Explain the word-RAM speedups of Masek–Paterson (O(n2/log⁡n)O(n^2/\log n)) and Myers (O(⌈m/w⌉ n)O(\lceil m/w \rceil\, n)).
  • State the SETH-based lower bound, sketch its reduction from orthogonal vectors, and summarize the state of approximation as of 2025.

The recurrence and two structural facts

The edit distance ed(a,b)\mathrm{ed}(a, b) is the fewest single-character insertions, deletions and substitutions that turn aa into bb, ∣a∣=n\abs a = n and ∣b∣=m\abs b = m. It is a metric (symmetric, and it obeys the triangle inequality), and the Wagner–Fischer table computes it: D[i][j]=ed(a[0..i),b[0..j))D[i][j] = \mathrm{ed}(a[0..i), b[0..j)), with

D[i][j]=min⁡(D[i−1][j−1]+[ a[i−1]≠b[j−1] ], D[i−1][j]+1, D[i][j−1]+1),D[i][j] = \min\big(D[i-1][j-1] + [\,a[i-1] \ne b[j-1]\,],\ D[i-1][j] + 1,\ D[i][j-1] + 1\big),

D[i][0]=iD[i][0] = i and D[0][j]=jD[0][j] = j. The table is the edit graph: an alignment is a path from (0,0)(0, 0) to (n,m)(n, m), and horizontal and vertical steps each cost 1. Faster algorithms rest on two facts about this table.

DerivationProofs
  1. D[i][j] ≥ ∣i−j∣D[i][j]\ \ge\ \abs{i - j}

    Band. A path from (0,0)(0, 0) to (i,j)(i, j) takes at least ∣i−j∣\abs{i - j} horizontal or vertical steps, each costing 1. A path to (n,m)(n, m) through a cell with ∣j−i∣>k\abs{j - i} > k already costs more than kk there, so it cannot be optimal when ed(a,b)≤k\mathrm{ed}(a, b) \le k:

  2. ∣D[i][j]−D[i−1][j]∣≤1,∣D[i][j]−D[i][j−1]∣≤1\abs{D[i][j] - D[i-1][j]} \le 1, \qquad \abs{D[i][j] - D[i][j-1]} \le 1

    Neighbors. D[i][j]≤D[i−1][j]+1D[i][j] \le D[i-1][j] + 1 by the delete option. Conversely, remove a[i−1]a[i-1] from an optimal alignment of a[0..i)a[0..i) with b[0..j)b[0..j): if it was deleted, the cost drops by 1; if it was aligned with a letter of bb, that letter becomes an insertion and the cost rises by at most 1. Columns are symmetric:

  3. D[i−1][j−1] ≤ D[i][j] ≤ D[i−1][j−1]+1D[i-1][j-1]\ \le\ D[i][j]\ \le\ D[i-1][j-1] + 1

    Diagonals. Each option for D[i][j]D[i][j] is at least D[i−1][j−1]D[i-1][j-1]: the first adds 0 or 1 to it, and the other two, D[i−1][j]+1D[i-1][j] + 1 and D[i][j−1]+1D[i][j-1] + 1, are at least D[i−1][j−1]D[i-1][j-1] by the neighbor bound. The substitution option gives the upper bound:

Small distances: bands and diagonals

Banded DP. To decide whether ed(a,b)≤k\mathrm{ed}(a, b) \le k, fill only the 2k+12k + 1 diagonals ∣j−i∣≤k\abs{j - i} \le k and treat every other cell as +∞+\infty. By the band lemma the answer is right whenever it is at most kk, in O(nk)O(nk) time. Not knowing DD in advance, try k=1,2,4,…k = 1, 2, 4, \dots: the last run dominates, so the total is O(n⋅D)O(n \cdot D). Ukkonen (1985) and Myers (1986) obtained bounds of this O(nD)O(nD) type.

Diagonal transitions. The diagonal lemma says each diagonal is a staircase of values, so it is described by where its value increases. Let Le(d)L_e(d) be the furthest row ii on diagonal d=j−id = j - i with D[i][i+d]≤eD[i][i + d] \le e. One more edit moves to a neighboring diagonal or one step along the same one, and then matches are free:

Le(d)=slided(max⁡(Le−1(d)+1, Le−1(d+1)+1, Le−1(d−1))),L_e(d) = \mathrm{slide}_d\Big(\max\big(L_{e-1}(d) + 1,\ L_{e-1}(d+1) + 1,\ L_{e-1}(d-1)\big)\Big),

where slided(i)\mathrm{slide}_d(i) follows equal letters along diagonal dd. The distance is the first ee with Le(m−n)=nL_e(m - n) = n.

python
def edit_distance_diag(a, b):
    """Levenshtein distance by diagonal transitions: O((n + m) * D) time."""
    n, m = len(a), len(b)
    def slide(i, d):                       # follow matches along diagonal d = j - i
        while i < n and i + d < m and a[i] == b[i + d]:
            i += 1
        return i
    far = {0: slide(0, 0)}                 # cost 0: furthest row on diagonal 0
    e = 0
    while far.get(m - n, -1) < n:          # (n, m) not reached yet
        e += 1
        nxt = {}
        for d in range(-e, e + 1):
            i = max(far.get(d, -2) + 1,        # substitute: same diagonal
                    far.get(d + 1, -2) + 1,    # delete a[i]: from diagonal d + 1
                    far.get(d - 1, -2))        # insert b[j]: from diagonal d - 1
            i = min(i, n, m - d)               # clamp to the table
            if i >= max(0, -d):                # a real cell of diagonal d
                nxt[d] = slide(i, d)
        far = nxt
    return e

print(edit_distance_diag('saturday', 'sunday'))   # 3

For cost ee only diagonals −e…e-e \dots e matter, and each slide only moves forward, so the time is O((n+m) D)O((n + m)\,D); this is Myers's O(ND)O(ND) algorithm (1986) adapted to substitutions. Clamping at the border is safe because neighbors differ by at most 1. Checked against the full table on thousands of random pairs, including 300-letter DNA strings with up to 20 edits.

Check your understanding

Two DNA reads of length 10610^6 are known to differ by at most 50 edits. Which method computes their edit distance fastest?

  1. The full Wagner–Fischer table: 101210^{12} cells
  2. The band of 101 diagonals: about 10810^8 cells
  3. Diagonal transitions with constant-time extensions: about 106+50210^6 + 50^2 steps
  4. Hirschberg's algorithm, which is faster than the table
Show the answer

C. Diagonal transitions with constant-time extensions: about 106+50210^6 + 50^2 steps

With LCE queries in O(1)O(1) after linear preprocessing, the O(k2)O(k^2) diagonal transitions cost about 2,500 steps on top of the O(n)O(n) preprocessing. The band is a big improvement on the full table but still about 10810^8 cells; Hirschberg's method saves space, not time.

Word-level parallelism

Four Russians. Cut the table into t×tt \times t blocks. By the neighbor lemma, a block's top row and left column are described by 2t2t differences in {−1,0,1}\{-1, 0, 1\}, and its bottom row and right column, again as differences, depend only on those and on the 2t2t letters it compares. Over a constant alphabet Σ\Sigma there are (3∣Σ∣)2t(3\abs\Sigma)^{2t} kinds of block; with t=14log⁡3∣Σ∣nt = \tfrac14 \log_{3\abs\Sigma} n that is n\sqrt n kinds, all precomputed in o(n2)o(n^2) time. Filling (n/t)2(n/t)^2 blocks at O(t)O(t) each then takes O(n2/t)=O(n2/log⁡n)O(n^2/t) = O(n^2 / \log n) time (Masek & Paterson, 1980, for a finite alphabet and suitably restricted costs).

Bit vectors. Myers (1999) stores a whole column of vertical differences in two bit vectors (where the difference is +1+1, and where it is −1-1) and advances to the next column with a constant number of word operations (and, or, xor, addition, shifts) per ww rows. For a pattern of length m≤wm \le w, 64 on today's processors, each text character costs O(1)O(1) word operations: O(⌈m/w⌉ n)O(\lceil m/w \rceil\, n) in all. It was designed for approximate pattern matching, and with a different boundary row it computes the edit distance of two whole strings; fast alignment libraries are built on it.

Exact algorithmTimeBest when
Wagner–Fischer (1974)O(nm)O(nm)Simplicity; any costs
Banded DP, doubling kkO(nD)O(n D)The distance DD is small
Diagonal transitions (Ukkonen, 1985; Myers, 1986)O((n+m)D)O((n + m) D)Small DD, no index needed
Landau–Vishkin (1988)O(n+k2)O(n + k^2) to decide D≤kD \le kVery small kk; needs constant-time extensions
Masek–Paterson (1980)O(n2/log⁡n)O(n^2/\log n)Theory: constant alphabet, restricted costs
Myers's bit vectors (1999)O(⌈m/w⌉ n)O(\lceil m/w \rceil\, n)Practice: a factor of about ww over the table
Exact unit-cost edit distance. Every row is quadratic in the worst case, up to a logarithmic or word-size factor, for a reason the next step explains.

The SETH barrier, and approximation

DerivationSETH makes OV quadratic (Williams, 2005)
  1. uα[c]=1  ⟺  α leaves clause c unsatisfiedu_\alpha[c] = 1 \iff \alpha \text{ leaves clause } c \text{ unsatisfied}

    Split the NN variables of a CNF formula φ\varphi with MM clauses into two halves. For each assignment α\alpha of the first half, let uα∈{0,1}Mu_\alpha \in \{0, 1\}^M have a 1 in coordinate cc exactly when α\alpha satisfies no literal of clause cc; define vβv_\beta in the same way for the second half.

  2. α∪β satisfies φ  ⟺  uα⋅vβ=0\alpha \cup \beta \text{ satisfies } \varphi \iff u_\alpha \cdot v_\beta = 0

    The combined assignment satisfies clause cc iff at least one half does, that is iff uα[c] vβ[c]=0u_\alpha[c]\, v_\beta[c] = 0. So φ\varphi is satisfiable iff some pair is orthogonal:

  3. (2N/2)2−δ=2(1−δ/2)N\big(2^{N/2}\big)^{2-\delta} = 2^{(1-\delta/2)N}

    Each side has 2N/22^{N/2} vectors. An OV algorithm running in O(NOV2−δ poly(d))O(N_{\mathrm{OV}}^{2-\delta}\,\mathrm{poly}(d)) time would solve kk-SAT in O(2(1−δ/2)N poly(M))O(2^{(1-\delta/2)N}\,\mathrm{poly}(M)) time for every kk, and the sparsification lemma lets MM be linear in NN: SETH would be false.

What the theorem does and does not say. It rules out O(n2−δ)O(n^{2-\delta}) algorithms under a hypothesis, not unconditionally, and it does not rule out the n2/log⁡nn^2/\log n-type speedups that exist. Even large polylogarithmic speedups, though, would imply new circuit lower bounds (Abboud, Hansen, Vassilevska Williams & Williams, STOC 2016). It concerns exact distances in the worst case: small distances, special inputs and approximation are fair game.

Approximation. Chakraborty, Das, Goldenberg, Koucký and Saks (FOCS 2018) gave the first constant-factor approximation in truly subquadratic time, about O~(n2−2/7)\tilde O(n^{2-2/7}). Andoni and Nosatzki (FOCS 2020) reached near-linear time: for every ε>0\varepsilon > 0, a constant-factor approximation (the constant depends on ε\varepsilon) in O(n1+ε)O(n^{1+\varepsilon}) time.

Key takeaways

  • Every cell satisfies D[i][j]≥∣i−j∣D[i][j] \ge \abs{i - j}, and diagonals rise in steps of 0 or 1. So a distance of at most kk lives in a band of 2k+12k + 1 diagonals (O(nk)O(nk) time), and each diagonal is described by where its value increases.
  • Diagonal transitions compute the distance in O((n+m)D)O((n + m)D), and with constant-time longest common extensions in O(n+k2)O(n + k^2) (Landau & Vishkin): linear time for small distances.
  • Word-level parallelism speeds up the table: the Four Russians reach O(n2/log⁡n)O(n^2/\log n) (Masek & Paterson), and Myers's bit vectors use O(⌈m/w⌉ n)O(\lceil m/w \rceil\, n) word operations.
  • Under SETH, through orthogonal vectors, no O(n2−δ)O(n^{2-\delta}) algorithm exists (Backurs & Indyk, 2015), and big polylogarithmic speedups would imply circuit lower bounds; approximation escapes the barrier, with constant factors in near-linear time (Andoni & Nosatzki, 2020).

Check yourself

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

Question 1

If ed(a,b)≤k\mathrm{ed}(a, b) \le k, which cells can an optimal alignment path visit?

  1. Only cells on the main diagonal i=ji = j
  2. Only cells with ∣j−i∣≤k\abs{j - i} \le k
  3. Only cells with i+j≤ki + j \le k
  4. Any cell: the band only helps on random strings
Show the answer

B. Only cells with ∣j−i∣≤k\abs{j - i} \le k

Reaching (i,j)(i, j) costs at least ∣i−j∣\abs{i - j} horizontal or vertical steps, each worth 1, so a cell off the band already costs more than kk. This is why a band of 2k+12k + 1 diagonals suffices.

Question 2

Why does the diagonal-transition algorithm only need the furthest row reached on each diagonal for each cost?

  1. Because values along a diagonal never decrease and rise by at most 1 per step, so each diagonal is a staircase described by where it steps up
  2. Because optimal paths never use insertions
  3. Because the alphabet is finite
  4. Because the furthest row always holds the smallest value
Show the answer

A. Because values along a diagonal never decrease and rise by at most 1 per step, so each diagonal is a staircase described by where it steps up

By the diagonal lemma, the cells of diagonal dd with value at most ee form a prefix of the diagonal. Recording where that prefix ends, for each ee, describes the whole diagonal, and one edit plus free matches moves from cost e−1e - 1 to cost ee.

Question 3

What does the Backurs–Indyk theorem say?

  1. Every algorithm for edit distance needs Ω(n2)\Omega(n^2) time
  2. If edit distance has an O(n2−δ)O(n^{2-\delta}) algorithm for some δ>0\delta > 0, then the Strong Exponential Time Hypothesis is false
  3. Edit distance is NP-hard
  4. Approximating edit distance within any constant factor requires quadratic time
Show the answer

B. If edit distance has an O(n2−δ)O(n^{2-\delta}) algorithm for some δ>0\delta > 0, then the Strong Exponential Time Hypothesis is false

It is a conditional, fine-grained statement: a strongly subquadratic algorithm would, through orthogonal vectors, solve kk-SAT in O(2(1−ε)N)O(2^{(1-\varepsilon)N}) time for every kk. It does not rule out n2/log⁡nn^2/\log n, which Masek and Paterson achieve, and approximation escapes it altogether.

Question 4

Myers's bit-vector algorithm compares a pattern of length m≤64m \le 64 with a text of length nn on a 64-bit machine. About how many word operations does it use?

  1. O(n)O(n): a constant number per text character
  2. O(nm)O(nm), like the table
  3. O(nlog⁡m)O(n \log m)
  4. O(m2)O(m^2)
Show the answer

A. O(n)O(n): a constant number per text character

A column of the table, one text character against all m≤wm \le w pattern positions, is held as bit vectors of vertical differences, and advancing to the next column takes a constant number of word operations. In general the cost is O(⌈m/w⌉ n)O(\lceil m/w \rceil\, n), about ww times fewer steps than the table.

Further reading

  • R. A. Wagner & M. J. Fischer, "The string-to-string correction problem," Journal of the ACM 21(1) (1974), 168–173.
  • E. Ukkonen, "Algorithms for approximate string matching," Information and Control 64 (1985), 100–118.
  • 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. Backurs & P. Indyk, "Edit distance cannot be computed in strongly subquadratic time (unless SETH is false)," STOC 2015.
  • A. Andoni & N. S. Nosatzki, "Edit distance in near-linear time: it's a constant factor," FOCS 2020.