Sub topic 4
Filling the Table by Interval Length
This chapter assumes you already know three things from earlier in the tutorial. First, that dp[i][j] holds the answer for the contiguous range from index i to index j. Second, that single-element ranges are base cases. Third, that a split-point recurrence combines dp[i][k] and dp[k + 1][j]. It also assumes you can read nested Python loops and two-dimensional lists.
A correct recurrence still gives wrong answers if you compute the table in the wrong order. Tabulation only works if every cell a recurrence reads has already been filled. In interval DP, the usual row-by-row loop breaks this rule. This chapter explains why it breaks, which orders are safe, and how to check an order mechanically.
What a Cell Depends On
Take the split-point recurrence:
dp[i][j]= best overkini..j-1of combine(dp[i][k],dp[k + 1][j])
Every cell it reads covers a range strictly inside [i, j]. The left piece [i, k] has length k - i + 1, which is at most j - i. The right piece [k + 1, j] has length j - k, which is also at most j - i. So both pieces are strictly shorter than the interval being computed.
The endpoint-shrinking recurrence, covered in a later chapter, reads dp[i + 1][j], dp[i][j - 1], and dp[i + 1][j - 1]. Those cells are also strictly shorter. Every interval recurrence in this tutorial shares this property, and it gives you a safe order: compute all intervals of length 1, then all of length 2, and so on up to length n.
Where Row-Major Order Goes Wrong
The habit from grid DP is for i in range(n): for j in range(n). In interval DP, dp[0][3] needs dp[1][3], which sits in row 1. Row 1 has not been touched while row 0 is being filled. In Python the unfilled cell still holds its initial value, usually 0 or infinity, so the code raises no error. It reads the placeholder and returns a plausible wrong number.
To see this happen, count the ways to fully parenthesize a product of n items. The recurrence is ways[i][j] = sum(ways[i][k] * ways[k + 1][j]) with ways[i][i] = 1. The correct answers are the Catalan numbers, so 5 items give 14.
def count_ways_length_order(n):
ways = [[0] * n for _ in range(n)]
for i in range(n):
ways[i][i] = 1
for length in range(2, n + 1): # length 1 is the base case
for i in range(n - length + 1): # last valid start index
j = i + length - 1 # inclusive end index
ways[i][j] = sum(ways[i][k] * ways[k + 1][j] for k in range(i, j))
return ways[0][n - 1]
def count_ways_row_major(n):
ways = [[0] * n for _ in range(n)]
for i in range(n):
ways[i][i] = 1
for i in range(n): # WRONG: row 0 is finished first
for j in range(i + 1, n):
ways[i][j] = sum(ways[i][k] * ways[k + 1][j] for k in range(i, j))
return ways[0][n - 1]
def count_ways_reverse_rows(n):
ways = [[0] * n for _ in range(n)]
for i in range(n - 1, -1, -1): # bottom row first
ways[i][i] = 1
for j in range(i + 1, n): # left to right within the row
ways[i][j] = sum(ways[i][k] * ways[k + 1][j] for k in range(i, j))
return ways[0][n - 1]
print(count_ways_length_order(5)) # 14
print(count_ways_row_major(5)) # 1
print(count_ways_reverse_rows(5)) # 14The row-major version prints 1. In row 0, every ways[k + 1][j] with k + 1 < j is still 0, so only the split k = j - 1 contributes. Each cell just copies its left neighbor.
The Length-Major Loop, Line by Line
Most bugs in the standard loop are off-by-one errors. Here is what each line does with inclusive bounds:
| Line | Purpose | Common mistake |
|---|---|---|
| `for length in range(2, n + 1)` | Lengths 2 through `n`; length 1 was set as a base case | Starting at 1 overwrites base cases with an empty `min`/`sum` |
| `for i in range(n - length + 1)` | Start indices whose interval fits: `i + length - 1 <= n - 1` | Using `range(n - length)` skips the last interval, including `[0, n-1]` when `length == n` |
| `j = i + length - 1` | Inclusive end index | Writing `j = i + length` reads one past the range |
| `for k in range(i, j)` | Splits leave both sides non-empty | `range(i, j + 1)` makes `dp[k + 1][j]` an empty or out-of-bounds range |
| reset `dp[i][j] = INF` before the `k` loop | Minimization starts fresh | Leaving 0 from initialization makes every minimum 0 |
For n = 4, length-major order fills the upper triangle one diagonal at a time. In the table below, the numbers give fill order, B marks base cases, and - marks cells that are never used because i > j.
| i \ j | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| 0 | B | 1 | 4 | 6 |
| 1 | - | B | 2 | 5 |
| 2 | - | - | B | 3 |
| 3 | - | - | - | B |
Other Valid Orders
Length order is one valid order among several. Any order that fills a cell after every cell it reads will work. For interval recurrences, the safe orders are:
| Order | Loops | Why it is safe |
|---|---|---|
| By length (diagonals) | `length` ascending, then `i` | All reads are strictly shorter |
| Rows bottom-up | `i` descending, `j` ascending | Row `i + 1` and beyond are complete. In row `i`, columns `< j` are done |
| Columns left-to-right | `j` ascending, `i` descending | Columns `< j` are complete. In column `j`, rows `> i` are done |
| Row-major ascending | `i` ascending, `j` ascending | **Unsafe**: reads row `i + 1` before it exists |
How to choose:
- Length order fits problems that cap the length, such as circular sequences where only intervals up to length
nmatter in a doubled array. It also fits Knuth's optimization, whose boundsopt[i][j - 1]andopt[i + 1][j]both come from the previous length. - Bottom-up rows fit endpoint-shrinking recurrences well, because the code reads like the recurrence:
i + 1is ready, and so isj - 1. The palindrome chapter uses this form. - Memory access differs a little between orders. The inner
kloop scansdp[i][k]along a row anddp[k + 1][j]down a column whichever order you pick. In compiled languages, keeping a transposed copy so the column reads become row reads can speed things up for largen. In Python, this effect is usually lost in interpreter overhead.
Exclusive and Open Bounds
The loop shape depends on how you define the bounds. Change the loop when you change the definition.
- Half-open
[i, j): length isj - i, and the base case islength == 1withj = i + 1. The loop becomesfor length in range(2, n + 1): for i in range(n - length + 1): j = i + length. Splits usekinrange(i + 1, j), and the pieces are[i, k)and[k, j). - Open
(left, right): this form appears in burst balloons, where the interval holds the elements strictly between two sentinels. The empty interval hasright - left == 1and value 0. Loop the gap from 2 up to the padded length minus 1.
Whichever form you use, the rule stays the same: compute a cell only after every strictly smaller interval is done.
Checking an Order Mechanically
When you design an unusual order, you can test it instead of reasoning by hand. The checker below replays an order against the split-point dependencies and reports the first cell that is read before it is written.
def check_order(n, order):
filled = {(i, i) for i in range(n)}
for i, j in order:
for k in range(i, j):
for cell in ((i, k), (k + 1, j)):
if cell not in filled:
return f"dp[{i}][{j}] reads unfilled dp[{cell[0]}][{cell[1]}]"
filled.add((i, j))
return "ok"
n = 5
by_length = [(i, i + L - 1) for L in range(2, n + 1) for i in range(n - L + 1)]
row_major = [(i, j) for i in range(n) for j in range(i + 1, n)]
by_column = [(i, j) for j in range(n) for i in range(j - 1, -1, -1)]
print(check_order(n, by_length)) # ok
print(check_order(n, row_major)) # dp[0][2] reads unfilled dp[1][2]
print(check_order(n, by_column)) # okTo check an endpoint recurrence, change the inner reads to (i + 1, j), (i, j - 1), and (i + 1, j - 1). When i + 1 > j - 1, skip the read or treat it as an empty base case.
Exercise
In countwayslength_order, someone writes for i in range(n - length): instead of range(n - length + 1). What does the function return for n = 5, and why?
Show answer
It returns 0. When length == n, range(0) is empty, so ways[0][4] is never computed and keeps its initial value 0. The same mistake also skips the last interval of every other length.
Exercise
Is the order "j descending, i ascending" (for j from n-1 down to 0, for i from 0 up to j-1) valid for the split-point recurrence? Give a specific failing read if it is not.
Show answer
It is not valid. The first cell filled is dp[0][n-1], which reads dp[0][k] for k < n-1. Those cells are in columns not yet processed. For n = 3 the first cell is dp[0][2], and at k = 0 it reads dp[1][2], which is unfilled.
Exercise
An endpoint recurrence reads dp[i+1][j], dp[i][j-1], and dp[i+1][j-1]. Explain why "i descending, j ascending" satisfies all three reads.
Show answer
When row i is being filled, every row greater than i is already complete, so dp[i+1][j] and dp[i+1][j-1] are ready. Within row i, j increases, so dp[i][j-1] was computed in the previous step of the same row (or is the base case dp[i][i]).