Sub topic 15
Why Quadratic Time Is Hard to Beat
Every exact algorithm in this tutorial so far fills some or all of an (m+1) by (n+1) table. The banded method and Myers' bit-parallel method make that work smaller or faster, but in the worst case they still do about n² work on two strings of length n. This chapter explains why nobody has found a much faster exact algorithm. It also explains why researchers now think a much faster one does not exist.
This chapter assumes you know Big-O notation, the full-table and two-row Levenshtein implementations, and the idea of a reduction: solving problem X by turning its instances into instances of problem Y. You do not need any complexity theory beyond that.
What "beating quadratic" would mean
There are two kinds of speedup, and the hardness result applies to only one of them.
- Log-factor speedups. These shave a slowly growing factor off n². Masek and Paterson (1980) used the "Four Russians" technique, which precomputes small blocks of the table, to get O(n²/log n) time for a fixed alphabet. Myers' algorithm packs w table cells into one machine word, giving O(n·⌈m/w⌉) time.
- Strongly subquadratic algorithms. These run in O(n^(2−ε)) time for some constant ε > 0, such as O(n^1.99) or O(n^1.5). An algorithm like that would grow polynomially slower than n². No one has found one for exact edit distance.
The evidence that the second kind is out of reach is conditional. It assumes a widely believed conjecture about satisfiability and shows that a strongly subquadratic edit distance algorithm would break that conjecture.
The Strong Exponential Time Hypothesis
A CNF formula is an AND of clauses, where each clause is an OR of literals (variables or their negations). k-SAT asks whether some true/false assignment to the n variables makes every clause true when each clause has at most k literals. Trying all assignments takes about 2ⁿ steps.
The Strong Exponential Time Hypothesis (SETH) says that this brute force is close to optimal when k is large:
> For every ε > 0 there is a k such that k-SAT on n variables cannot be solved in O(2^((1−ε)n)) time.
SETH is unproven. It is a hypothesis, in the same category as P ≠ NP but stronger. Decades of SAT research have not refuted it. The best known algorithms for k-SAT do beat 2ⁿ, but their advantage shrinks toward zero as k grows, and that is the behavior SETH predicts.
The bridge problem: Orthogonal Vectors
Edit distance is not reduced from SAT directly. The proof goes through an intermediate problem.
Orthogonal Vectors (OV): You are given two sets A and B, each holding N vectors in {0,1}^d. Decide whether some a ∈ A and b ∈ B have dot product 0, meaning no coordinate where both are 1.
Checking every pair takes O(N²·d) time. Williams (2005) showed that if OV could be solved in O(N^(2−ε)·poly(d)) time, then SETH would be false. His reduction is called split-and-list:
- Split the n variables into two halves.
- For each of the 2^(n/2) assignments to the first half, build a vector with one coordinate per clause. The coordinate is 0 if this partial assignment already satisfies the clause and 1 otherwise. These vectors form set A.
- Build set B the same way from the second half.
- A pair (a, b) is orthogonal exactly when every clause is satisfied by at least one of the two halves. That happens exactly when the combined assignment satisfies the formula.
Now N = 2^(n/2). An OV algorithm running in N^(2−ε) time would solve SAT in 2^((1−ε/2)n) time, which contradicts SETH.
The code below implements the reduction and checks it against brute-force SAT on random formulas.
import itertools
import random
def partial_vectors(clauses, variables):
"""One 0/1 vector per assignment to `variables`; 1 means clause not yet satisfied."""
vectors = []
for bits in itertools.product([False, True], repeat=len(variables)):
assign = dict(zip(variables, bits))
vec = []
for clause in clauses:
satisfied = any(
abs(lit) in assign and assign[abs(lit)] == (lit > 0)
for lit in clause
)
vec.append(0 if satisfied else 1)
vectors.append(tuple(vec))
return vectors
def has_orthogonal_pair(A, B):
return any(all(x * y == 0 for x, y in zip(a, b)) for a in A for b in B)
def sat_via_ov(clauses, n):
half = n // 2
A = partial_vectors(clauses, list(range(1, half + 1)))
B = partial_vectors(clauses, list(range(half + 1, n + 1)))
return has_orthogonal_pair(A, B)
def sat_brute_force(clauses, n):
for bits in itertools.product([False, True], repeat=n):
if all(any(bits[abs(l) - 1] == (l > 0) for l in c) for c in clauses):
return True
return False
random.seed(1)
for _ in range(200):
n = random.randint(2, 8)
clauses = [
[random.choice([1, -1]) * random.randint(1, n) for _ in range(3)]
for _ in range(random.randint(1, 12))
]
assert sat_via_ov(clauses, n) == sat_brute_force(clauses, n)
print("split-and-list reduction agrees with brute force on 200 formulas")From Orthogonal Vectors to edit distance
Backurs and Indyk (2015) completed the chain. From an OV instance with N vectors of dimension d, they build two strings x and y, each of length O(N·poly(d)), and a threshold T. The edit distance of x and y is at most T exactly when an orthogonal pair exists.
The construction uses gadgets, which are short strings with carefully chosen distances:
- Coordinate gadgets encode one bit. Two coordinate gadgets cost less to align when at least one of their bits is 0, so a pair of 1s is the only expensive case.
- Vector gadgets join d coordinate gadgets. Aligning the gadget for a with the gadget for b costs one fixed amount if a·b = 0 and a strictly larger amount otherwise.
- Padding and alignment structure surround the vector gadgets. Any cheap alignment of x with y has to pair the vectors up along some shift, and the cheapest shift lines up an orthogonal pair if one exists.
The string lengths are n = O(N·poly(d)) and d = O(log N) in the hard instances. An O(n^(2−ε)) edit distance algorithm would therefore solve OV in O(N^(2−ε)·polylog N) time, and that would refute SETH.
Follow-up work made the result stronger:
- Bringmann and Künnemann (2015) showed the same barrier holds for binary strings, and also for longest common subsequence and dynamic time warping. The indel distance from the LCS chapter does not escape it.
- Abboud, Hansen, Vassilevska Williams, and Williams (2016) showed that shaving more than a polylogarithmic factor, for example reaching n²/log^(ω(1)) n, would imply new circuit lower bounds that have resisted proof for decades. Even large log-factor speedups look out of reach.
What you can still do
The lower bound covers exact distance on worst-case inputs with no extra assumptions. Every practical speedup gets around one of those three conditions.
| Approach | Running time | Which condition it relaxes |
|---|---|---|
| Banded / Ukkonen, Landau-Vishkin | O(n·d) or O(n + d²) for distance d | Worst case: fast when strings are similar |
| Myers bit-parallel | O(n·⌈m/w⌉) | Only a constant (word-size) factor; still quadratic |
| Four Russians (Masek-Paterson) | O(n²/log n) | Only a log factor; consistent with SETH |
| Constant-factor approximation (Chakraborty et al., 2018) | O(n^(2−ε)) for some ε > 0 | Exactness |
| Near-linear polylog approximation (Andoni-Krauthgamer-Onak, 2010) | n^(1+o(1)) | Exactness |
| Filtering with q-grams or seeds | Depends on input | Exactness for pairs ruled out early |
When d is small compared with n, the Landau-Vishkin bound O(n + d²) is close to linear. The hard instances from the reduction have distances close to n, so they do not contradict it.
Seeing the quadratic growth
The lower bound concerns asymptotic growth, but the n² behavior is easy to measure. When n doubles, the two-row implementation does about four times the work.
import random
import time
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]
random.seed(0)
previous = None
for n in (250, 500, 1000, 2000):
a = "".join(random.choice("ACGT") for _ in range(n))
b = "".join(random.choice("ACGT") for _ in range(n))
start = time.perf_counter()
levenshtein_two_rows(a, b)
elapsed = time.perf_counter() - start
ratio = f"{elapsed / previous:.1f}x" if previous else "-"
print(f"n={n:5d} time={elapsed:.3f}s ratio vs previous={ratio}")
previous = elapsedThe ratios should come out close to 4. Extrapolating from the measurements, two strings of length 10⁶ need 10¹² cell updates. That takes hours in pure Python and minutes even in tight C. This is why large-scale systems lean on the table's approaches.
Decision criteria
- Exact distance, short strings (up to a few thousand characters): use the quadratic DP or Myers' algorithm. The lower bound does not matter at this size.
- Exact distance, long strings, small expected distance: use a banded or Landau-Vishkin method. Its cost depends on d, not on n².
- Long strings, large distance, ranking or clustering: use an approximation or a filter. Exact answers at this scale cost quadratic time, and SETH suggests no clever trick will avoid that.
- Before you try to "optimize" the core DP: expect constant-factor and log-factor gains, not a better exponent.
Exercise
In split-and-list, suppose you had an Orthogonal Vectors algorithm running in O(N^1.9 · d) time. How fast would it solve CNF-SAT with n variables and c clauses, and why does that contradict SETH?
Show answer
Each half has n/2 variables, so N = 2^(n/2) and d = c. The time is O((2^(n/2))^1.9 · c) = O(2^(0.95n) · c), plus O(2^(n/2) · c) to build the vectors. That beats 2^((1−ε)n) with ε = 0.05 for every clause width k. SETH says some k makes k-SAT require more than 2^(0.95n) time, so the two cannot both hold.
Exercise
A colleague announces an exact edit distance algorithm running in O(n² / log² n) time on binary strings. Does this refute SETH? What would?
Show answer
It does not. O(n²/log² n) is not O(n^(2−ε)) for any constant ε > 0, so the Backurs-Indyk reduction says nothing against it. (Abboud et al. place the barrier for log-factor gains at n²/log^(ω(1)) n, which is still beyond log² n.) Refuting SETH through this route would take an exact O(n^(2−ε)) algorithm that works on worst-case inputs.
Exercise
You must compare pairs of 500,000-character DNA reads, and most pairs differ in fewer than 1,000 positions. Does the quadratic lower bound mean the job is infeasible? Which method fits?
Show answer
It does not. The lower bound is about worst-case inputs, and the hard instances have distance close to n. With d ≤ 1,000, a banded method costs about n·d = 5·10⁸ cell updates, and Landau-Vishkin costs O(n + d²) ≈ 1.5·10⁶ steps. Both are far below n² = 2.5·10¹¹. Use a threshold-bounded method, and fall back to "distance > threshold" for pairs that exceed the band.