For my algorithms course, I solved three variants of the text segmentation problem with dynamic programming, proved them correct, and stress-tested them.
The most useful part wasn't the algorithms. It was looking at my stress test results and realising one of them made no sense.
The problem
You get a string of letters with no spaces, and a function IsWord(s) that tells you whether s is a valid word. The three tasks:
(a) Count the ways to split one string into words.
ARTISTOIL has two splits: ARTIST · OIL and ART · IS · TOIL.
(b) Decide whether two strings can be split at the same positions.
BOTHEARTHANDSATURNSPIN and PINSTARTRAPSANDRAGSLAP can:
BOT · HEART · HAND · SAT · URNS · PIN PIN · START · RAPS · AND · RAGS · LAP (c) Count the ways to split two strings at the same positions.
The assignment asked us to keep calls to IsWord low, since in real life a dictionary lookup might be expensive.
The DP
All three follow the same pattern. dp[i] holds the answer for the first i characters. To fill it, try every possible last word A[j:i]:
def count_partitions(A: str) -> int: n = len(A) dp = [0] * (n + 1) dp[0] = 1 # one way to split the empty string for i in range(1, n + 1): for j in range(i): if IsWord(A[j:i]): dp[i] += dp[j] return dp[n] Variant (b) swaps the count for a boolean and checks both strings:
def can_partition_same_indices(A: str, B: str) -> bool: n = len(A) dp = [False] * (n + 1) dp[0] = True for i in range(1, n + 1): for j in range(i): if IsWord(A[j:i]) and IsWord(B[j:i]) and dp[j]: dp[i] = True break return dp[n] Two nested loops, so O(n²) calls to IsWord. I proved each one correct by induction on i.
The stress test
To simulate the worst case, I made IsWord always return True, so every substring counts as a word. Then I timed each function on random strings:
| n | (a) count | (b) decide | (c) count both |
|---|---|---|---|
| 500 | 0.048 s | 0.0002 s | 0.046 s |
| 1000 | 0.206 s | 0.0006 s | 0.180 s |
| 1500 | 0.485 s | 0.0008 s | 0.442 s |
| 2000 | 0.508 s | 0.0011 s | 0.973 s |
Look at column (b). It's hundreds of times faster than the others and grows roughly linearly. An O(n²) algorithm shouldn't do that.
What was actually happening
With IsWord always True, the very first check in the inner loop (j = 0) succeeds, because dp[0] is True. Then break exits immediately. So the inner loop runs once per i, and the whole thing is O(n).
My "worst case" was actually the best case for (b).
The real worst case for (b) is the opposite: no substring is a word, so the loop never breaks. I counted the IsWord calls in both situations:
| n | IsWord always True | IsWord always False |
|---|---|---|
| 500 | 1,000 | 125,250 |
| 2,000 | 4,000 | 2,001,000 |
That's the O(n²) behaviour, and my original test never showed it.
The one-line improvement
Look at the condition again:
if IsWord(A[j:i]) and IsWord(B[j:i]) and dp[j]: dp[j] is a free array lookup, but it's checked last. If there's no valid split ending at j, we've already paid for two dictionary lookups for nothing. Python's and short-circuits, so moving the cheap check first skips them:
if dp[j] and IsWord(A[j:i]) and IsWord(B[j:i]): In the all-False case at n = 2,000, that drops IsWord calls from 2,001,000 to 2,000. Same algorithm, same big-O on paper, but far fewer of the expensive operation the assignment told us to minimise.
A second surprise: the numbers themselves
There's one more thing hiding in columns (a) and (c). When every substring is a word, the number of splits of an n-letter string is 2ⁿ⁻¹. At n = 2,000, dp[n] is a 2,000-bit integer.
Python handles big integers automatically, but adding them isn't constant time. Slicing A[j:i] also copies characters. So the "O(n²)" analysis quietly assumes O(1) additions and O(1) slicing, and neither is true here. That's part of why the measured times don't follow a clean n² curve.
What I learned
- Check that your worst-case test really is the worst case. Reason about which input makes each loop run longest.
- Measure the operation you care about. Counting
IsWordcalls was far more informative than wall-clock time. - Order matters in boolean conditions. Put cheap checks first and let short-circuiting do the work.
- Big-O hides assumptions. Arithmetic and slicing aren't always O(1).
The notebook, with the proofs and plots, is on GitHub.
