Sub topic 9
Counting States and Transitions: O(n^2) Space, O(n^3) Time
This chapter assumes you have already seen the split-point recurrence (matrix chain multiplication) and the endpoint-shrinking recurrence (longest palindromic subsequence). It also assumes you can read Big-O notation and sum simple series. The goal is to estimate the cost of any interval DP before you write it, and to spot the hidden extra factors that make it slower than you expected.
The Counting Rule
Every tabulated DP costs roughly:
- Space = number of states × size of each state
- Time = number of states × average work per state
Work per state is the number of transitions, meaning the candidate choices the recurrence compares, times the cost of evaluating each one. For interval DP, the states are contiguous ranges and the transitions are either split points or endpoint moves. If you count those two things, you know the complexity.
Counting the States
A state dp[i][j] with 0 <= i <= j < n stands for one non-empty contiguous range. Ranges of length L can start at n - L + 1 positions, so the total is:
| Length L | Number of intervals |
|---|---|
| 1 | n |
| 2 | n − 1 |
| ... | ... |
| n | 1 |
| **Total** | **n(n + 1) / 2** |
That gives Θ(n²) states. Allocating a full n × n table wastes the lower triangle where i > j. That waste is a constant factor of about 2, and it does not change the asymptotic bound. Some solutions read the cells below the diagonal on purpose as "empty interval" values. The palindrome recurrence does this when it reads dp[i + 1][j - 1] with j = i + 1. Keep that in mind before you compress the table into a triangular layout.
Counting the Transitions
Split-point recurrences
In matrix chain multiplication or stone merging, an interval of length L tries every split k with i <= k < j. That is L − 1 choices. Adding up over all intervals:
$$\sum_{L=1}^{n} (n - L + 1)(L - 1) = \frac{n^3 - n}{6}$$
The leading constant is 1/6, so the work is Θ(n³), but the total is about six times smaller than a naive n³. The count is exact, and you can check it by running the loop skeleton:
def count_split_transitions(n):
count = 0
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
for k in range(i, j):
count += 1
return count
for n in [1, 2, 3, 8, 50]:
print(n, count_split_transitions(n), (n**3 - n) // 6)
# 1 0 0
# 2 1 1
# 3 4 4
# 8 84 84
# 50 20825 20825The work is not spread evenly across lengths. Short intervals are numerous but have few splits. Long intervals have many splits but are rare. The product (n − L + 1)(L − 1) peaks near L = n/2.
Endpoint-shrinking recurrences
The longest palindromic subsequence recurrence looks at a constant number of neighbors: dp[i + 1][j - 1], dp[i + 1][j], and dp[i][j - 1]. With O(1) work per state, the total time is Θ(n²), the same as the state count. Before you assume an interval DP is cubic, check which recurrence shape it uses.
| Recurrence shape | States | Transitions per state | Time | Space |
|---|---|---|---|---|
| Endpoint shrinking | Θ(n²) | O(1) | Θ(n²) | Θ(n²), reducible to Θ(n) |
| Split point | Θ(n²) | Θ(j − i) | Θ(n³) | Θ(n²) |
| Split point with Knuth's condition | Θ(n²) | amortized O(1) | Θ(n²) | Θ(n²) |
The last row is covered in the final chapter. It is listed here so you know the cubic bound can sometimes be beaten.
Hidden Factors That Break the Estimate
The counting rule only holds if each transition really costs O(1). These are the common ways that assumption fails.
Recomputing the interval cost inside the split loop
Stone merging adds the total weight of piles[i..j] to each state. If you compute that sum with sum(piles[i:j + 1]) inside the k loop, each transition costs O(n) and the whole algorithm becomes Θ(n⁴). If you compute it once per state, outside the k loop, it adds only O(n) per state, which is O(n³) in total. That does not change the bound, but it doubles the constant. With prefix sums it costs O(1) per state, as a later chapter shows.
Expensive state values
A table of integers costs O(1) per cell. If a cell instead holds a string, such as a parenthesization built during the DP, then copying and concatenating it costs O(n) per transition. Store split indices instead, and rebuild the structure afterward in O(n). The reconstruction chapter uses this approach.
Top-down memoization
A memoized version of a split-point DP still visits all Θ(n²) states and still tries Θ(n) splits per state, so the bound stays the same. It adds function-call overhead and recursion depth of up to about n frames. In CPython, the default recursion limit of 1000 becomes a problem for inputs of a few hundred to a thousand elements. Memoization helps only when many states are unreachable, which is rare for split recurrences because every sub-interval is reachable from the full range.
Reducing Space
Endpoint recurrences: keep two rows
When i iterates downward, row i reads only row i + 1 and itself. You can therefore keep two rows of length n and reduce space to Θ(n):
def lps_two_rows(s):
n = len(s)
if n == 0:
return 0
prev = [0] * n # row i + 1
for i in range(n - 1, -1, -1):
cur = [0] * n
cur[i] = 1
for j in range(i + 1, n):
if s[i] == s[j]:
cur[j] = prev[j - 1] + 2 # prev[i] is 0 when j == i + 1: empty interval
else:
cur[j] = max(prev[j], cur[j - 1])
prev = cur
return prev[n - 1]
print(lps_two_rows("bbbab")) # 4The trade-off is that you lose the full table, so you can no longer trace back the actual subsequence. If you need the subsequence itself, keep the Θ(n²) table or use a divide-and-conquer reconstruction in the style of Hirschberg's algorithm.
Split recurrences: usually no reduction
dp[i][j] reads dp[i][k] for every k in its row and dp[k + 1][j] for every k in its column. Those cells span all lengths below j − i + 1, so no fixed-width window of the table contains everything a state needs. Θ(n²) space is the practical floor here.
From Big-O to Wall-Clock Time
Asymptotic bounds decide whether a solution is feasible, and the 1/6 constant decides how close to the limit you can go. As rough figures, CPython runs about 10⁷ simple loop iterations per second, and compiled languages run about 10⁸ to 10⁹.
| n | (n³ − n)/6 splits | CPython (approx.) | C++ / Java (approx.) | Full n×n table |
|---|---|---|---|---|
| 100 | 1.7 × 10⁵ | < 0.1 s | instant | 10⁴ cells |
| 500 | 2.1 × 10⁷ | several seconds | < 0.1 s | 2.5 × 10⁵ cells |
| 2,000 | 1.3 × 10⁹ | minutes | 1–3 s | 4 × 10⁶ cells |
| 10,000 | 1.7 × 10¹¹ | infeasible | infeasible | 10⁸ cells |
Memory becomes a problem sooner in Python than these cell counts suggest. A list of lists stores an 8-byte pointer per cell, so 10⁸ cells need about 800 MB before you count the integer objects. For large n, a flat array('q') or a NumPy array cuts that down a lot.
You can check the cubic growth by timing the skeleton. Each doubling of n should multiply the time by about 8:
import time
def split_skeleton(n):
count = 0
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
for k in range(i, j):
count += 1
return count
prev = None
for n in [100, 200, 400]:
start = time.perf_counter()
split_skeleton(n)
elapsed = time.perf_counter() - start
ratio = f"{elapsed / prev:.1f}x" if prev else "-"
print(f"n={n:4d} {elapsed:.3f}s growth {ratio}")
prev = elapsedAt small n the ratio comes out below 8, because fixed overheads still account for a large share of the run time. As n grows, the ratio approaches 8.
Exercise
How many split transitions does the bottom-up matrix chain algorithm evaluate for n = 10 matrices? Check your answer against the per-length sum.
Show answer
(10³ − 10)/6 = 990/6 = 165. By length: 9·1 + 8·2 + 7·3 + 6·4 + 5·5 + 4·6 + 3·7 + 2·8 + 1·9 = 9 + 16 + 21 + 24 + 25 + 24 + 21 + 16 + 9 = 165.
Exercise
A stone-merging solution writes dp[i][j] = min(dp[i][k] + dp[k+1][j] + sum(piles[i:j+1]) for k in range(i, j)). What is its time complexity, and what is the smallest change that restores O(n³)?
Show answer
The sum is evaluated once per split, so each transition costs O(n), giving Θ(n⁴) overall. Computing total = sum(piles[i:j+1]) once before taking the minimum restores Θ(n³). Prefix sums make the per-state cost O(1).
Exercise
Explain why the two-row space trick works for longest palindromic subsequence but not for matrix chain multiplication.
Show answer
In the palindrome recurrence, dp[i][j] reads only row i + 1 and earlier cells of row i, so two rows hold everything needed. In matrix chain, dp[i][j] reads dp[k + 1][j] for every k between i and j − 1, which is cells from many different rows in column j, so no constant number of rows is enough.
Exercise
A memoized top-down matrix chain solution runs for n = 3000 in CPython. Name two problems you should expect.
Show answer
First, about (3000³)/6 ≈ 4.5 × 10⁹ transitions, which is far too slow in CPython (hours). Second, recursion depth can exceed the default limit of 1000 and raise RecursionError. The 4.5 × 10⁶ cached entries in lru_cache also cost hundreds of megabytes.