Sub topic 6
How Much Time and Memory It Costs
This chapter assumes you can read Big-O notation, write a recursive Python function, and follow the table-filling implementation from the previous chapter. The question here is what that table costs to run. You will count the work, measure it, and see where the limits are before later chapters cut those costs down.
Counting the Cells
The dynamic programming table for strings a (length m) and b (length n) has (m + 1) rows and (n + 1) columns. Every cell is filled exactly once. Filling one cell takes a fixed amount of work: one character comparison, three additions, and a minimum over three values. None of that depends on m or n.
So the total work is proportional to the number of cells:
- Time: (m + 1)(n + 1) cell updates, which is O(mn).
- Space: (m + 1)(n + 1) stored integers, which is also O(mn).
When the two strings have similar length n, both become O(n²). Doubling the length of both strings multiplies the work by four.
The base row and base column add only m + n + 1 cells, so they do not change the order of growth. They matter for small inputs, though. Comparing a 1-character string with a 1-character string fills 4 cells, not 1.
Why the Table Matters: The Naive Recursion
The recurrence on its own suggests a recursive function with no table. That version is correct and very slow, because the same prefix pairs get solved over and over. The script below counts how many calls the naive version makes and compares that with the number of distinct subproblems.
def naive(a, b, calls):
calls[0] += 1
if not a:
return len(b)
if not b:
return len(a)
cost = 0 if a[-1] == b[-1] else 1
return min(
naive(a[:-1], b, calls) + 1,
naive(a, b[:-1], calls) + 1,
naive(a[:-1], b[:-1], calls) + cost,
)
for n in range(2, 10):
a = "a" * n
b = "b" * n
calls = [0]
d = naive(a, b, calls)
distinct = (n + 1) * (n + 1)
print(f"n={n} distance={d} calls={calls[0]:>9} distinct subproblems={distinct}")The call count grows by roughly a factor of 5 to 6 each time n goes up by one. Each call spawns three more, and the subproblems overlap heavily. The distinct subproblems grow only as (n + 1)². Dynamic programming wins by solving each of those once.
A memoized recursive version (for example with functools.lru_cache) also runs in O(mn) time and space. In Python it has two practical drawbacks:
- Recursion depth reaches m + n. CPython's default limit is 1000 frames, so two 600-character strings raise
RecursionErrorunless you raise the limit. - Each call goes through function-call and cache-lookup overhead, which is several times slower than an indexed list update in a loop.
The iterative table avoids both problems and has the same asymptotic cost.
Measuring It
Big-O tells you the shape of the growth, not the seconds. The script below times the full-table implementation and prints the ratio between successive runs. Because the length doubles each time, the ratio should approach 4.
import random
import string
import time
def levenshtein(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
cost = 0 if a[i - 1] == b[j - 1] else 1
dp[i][j] = min(
dp[i - 1][j] + 1,
dp[i][j - 1] + 1,
dp[i - 1][j - 1] + cost,
)
return dp[m][n]
def random_string(n):
return "".join(random.choices(string.ascii_lowercase, k=n))
random.seed(0)
previous = None
for n in [250, 500, 1000, 2000]:
a, b = random_string(n), random_string(n)
start = time.perf_counter()
levenshtein(a, b)
elapsed = time.perf_counter() - start
rate = (n + 1) ** 2 / elapsed / 1e6
ratio = f"{elapsed / previous:.2f}x" if previous else "-"
print(f"n={n:>5} time={elapsed:.3f}s ratio={ratio:>6} ~{rate:.1f}M cells/s")
previous = elapsedOn typical hardware, pure CPython fills a few million cells per second. That puts two 10,000-character strings (10⁸ cells) somewhere around half a minute or more. A compiled implementation in C or Rust does the same work 50 to 100 times faster, but the growth is still quadratic. A faster language shifts the curve down. It does not change the curve's shape.
Memory Is Often the First Wall
Time grows as mn, but so does memory, and memory usually fails first. A slow job finishes eventually. A job that runs out of RAM crashes.
In CPython, a list of lists stores one 8-byte pointer per cell. Small integers from -5 to 256 are cached and shared. Larger values are separate objects of about 28 bytes each, but a table for long strings holds many cells whose values exceed 256. The estimates below count pointers only, so they are lower bounds.
| Lengths (m × n) | Cells | Python list of lists (pointers only) | NumPy int32 array | Two rows of length n |
|---|---|---|---|---|
| 100 × 100 | about 10⁴ | about 80 KB | about 40 KB | about 1.6 KB |
| 1,000 × 1,000 | about 10⁶ | about 8 MB | about 4 MB | about 16 KB |
| 10,000 × 10,000 | about 10⁸ | about 800 MB | about 400 MB | about 160 KB |
| 100,000 × 100,000 | about 10¹⁰ | about 80 GB | about 40 GB | about 1.6 MB |
The last column previews the next big idea. Computing the distance only needs the previous row, so memory can drop to O(min(m, n)). The catch is that the edit script can no longer be recovered by walking back through a stored table. A later chapter covers the two-row version and Hirschberg's method, which gets the edit script back in linear space.
What You Can and Cannot Get for Free
Some facts bound the problem from both sides.
Lower limits on the answer that cost almost nothing to compute:
- The distance is at least |m − n|, because each insertion or deletion changes the length by one and substitutions do not change it.
- The distance is at most max(m, n). You can substitute the overlapping characters and then insert or delete the rest.
These checks take O(1) time once the lengths are known, and they can settle a question immediately. If you only need to know whether two strings are within distance 3 and their lengths differ by 5, you are done.
Limits on any algorithm:
- Any correct algorithm must read every character, so Ω(m + n) time is unavoidable.
- No known algorithm computes exact edit distance in O(n^(2 − ε)) time for any ε > 0 on general inputs. A later chapter explains why researchers believe none exists.
The gap between linear and quadratic is where the practical speedups covered later fit. Banded computation restricts the work to cells near the diagonal when the distance is known to be small. Bit-parallel methods pack many cells into one machine word. Both keep the worst case quadratic but improve common cases a great deal.
Common Mistakes When Reasoning About Cost
- Writing the cost as O(n²) when the strings have very different lengths. Comparing a 10-character query with a 1,000,000-character text costs about 10⁷ cells, not 10¹². Keep both variables.
- Assuming slicing is free. In the naive recursion,
a[:-1]copies the string, which adds O(length) work to every call. Index-based recursion avoids this, but the call count is still exponential. - Measuring a single tiny input. Interpreter startup and loop setup dominate small runs. Time several sizes and check the ratios.
- Forgetting that the full table is the same size for every pair of strings with those lengths. Identical strings cost as much as completely different ones unless you add an early exit or a band.
Exercise
Your service compares each incoming 50-character query against 200,000 stored product names, each about 40 characters long, using the full-table algorithm. Roughly how many cells are filled per query, and at 3 million cells per second in Python, how long does one query take?
Show answer
Each comparison fills about 51 × 41 ≈ 2,091 cells. Over 200,000 names that is about 4.2 × 10⁸ cells, which takes roughly 140 seconds at 3 million cells per second. That is far too slow for interactive use, which is why length filters, thresholds, banding, or indexes are needed.
Exercise
Two strings have lengths 1,200 and 1,450. Without filling any table, give the tightest lower and upper bounds on their Levenshtein distance that follow from the lengths alone.
Show answer
The lower bound is |1,450 − 1,200| = 250, since at least 250 insertions or deletions are needed to match lengths. The upper bound is max(1,200, 1,450) = 1,450: substitute the 1,200 overlapping positions and insert the remaining 250 characters.
Exercise
A memoized recursive implementation works on 300-character strings but crashes on two 700-character strings with RecursionError, even though the machine has plenty of memory. Explain the cause and give two fixes.
Show answer
Recursion depth reaches about m + n = 1,400 frames, which exceeds CPython's default limit of 1,000. One fix is to raise the limit with sys.setrecursionlimit, which still risks a C stack overflow for larger inputs. The better fix is to switch to the iterative bottom-up table, which has the same O(mn) cost and no recursion.