Sub topic 6
How Much Time and Memory It Costs
This chapter assumes you know Big-O notation, can read Python, and have already seen the dynamic programming table for Levenshtein distance from the previous chapter. Here we count what that table costs to build and to store.
Counting the work
For strings a of length m and b of length n, the table has (m + 1) × (n + 1) cells. Each cell is filled with a fixed amount of work: one character comparison, three lookups, and a min of three values. None of that depends on m or n, so each cell costs O(1).
That gives:
- Time: O(m · n)
- Space: O(m · n) for the full table
The cost depends on the product of the lengths. Comparing a 50,000-character string with a 20-character string fills about one million cells, which is cheap. Comparing two 50,000-character strings fills 2.5 billion cells, which is not.
What quadratic growth looks like
When both strings have length n, the table has about n² cells. Doubling n multiplies the work by four.
Memory grows the same way. A Python list slot holds an 8-byte reference, so a rough lower bound is 8 bytes per cell:
| Length of each string | Cells | Approximate memory |
|---|---|---|
| 100 | about 10,000 | 80 KB |
| 1,000 | about 1 million | 8 MB |
| 10,000 | about 100 million | 800 MB |
| 100,000 | about 10 billion | 80 GB |
Memory usually becomes the limit before time does. A program that takes a minute of CPU is slow but still finishes. A program that needs 80 GB never finishes at all.
Measuring it yourself
This script times the full-table algorithm as the length doubles. Expect each ratio to come out near 4.
import random
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 rand_str(n):
return "".join(random.choice("acgt") for _ in range(n))
previous = None
for n in [250, 500, 1000, 2000]:
a, b = rand_str(n), rand_str(n)
start = time.perf_counter()
levenshtein(a, b)
elapsed = time.perf_counter() - start
ratio = f"{elapsed / previous:.1f}x" if previous else "-"
print(f"n={n:5d} {elapsed:.3f}s ratio {ratio}")
previous = elapsedCommon mistakes
- Memoized recursion is O(m · n), but it can hit the recursion limit. It recurses about m + n levels deep, so Python's default limit of 1,000 fails on long inputs. Use the iterative table instead.
- The cost isn't O(max(m, n)²). When one string is short, the work is small, so say O(m · n).
- Saving time doesn't save memory. Faster cell updates don't change the O(m · n) table size. The next chapter cuts memory to O(min(m, n)).
Exercise
Your service compares strings of length 3,000 in 0.2 seconds with the full-table algorithm. Roughly how long will strings of length 12,000 take, and about how much memory will the table need at 8 bytes per cell?
Show answer
The length grows by a factor of 4, so the work grows by 4² = 16, giving about 3.2 seconds. The table has about 12,001 × 12,001 ≈ 144 million cells, so at 8 bytes per cell it needs about 1.15 GB.
Exercise
Which costs more: comparing a 1,000,000-character string to a 10-character string, or comparing two 5,000-character strings?
Show answer
The two 5,000-character strings cost more, at about 25 million cells. The other pair needs about 10 million cells (1,000,001 × 11), because the cost depends on the product m · n.