Sub topic 1
Thinking in Intervals: What dp[i][j] Means
Prerequisites
This chapter assumes you already know basic dynamic programming (memoization and tabulation), recursion, two-dimensional arrays, Big-O analysis, and how to read Python.
The Interval State
Interval DP applies when the best answer for a sequence can be built from the best answers for its contiguous subranges. The state dp[i][j] holds the optimal value for the slice from index i to index j.
Decide on the bounds before you write anything else:
| Convention | Range covered | Empty range | Full answer |
|---|---|---|---|
| Inclusive `[i, j]` | `a[i]..a[j]` | `j < i` | `dp[0][n-1]` |
| Half-open `[i, j)` | `a[i]..a[j-1]` | `j == i` | `dp[0][n]` |
Most off-by-one bugs here come from switching between these conventions partway through a solution.
Base Cases
Each interval eventually shrinks to an empty range or to a single element. These are the base cases, and their values come straight from the problem definition. In a minimum-cost problem, a single element usually costs 0 because there is nothing left to combine. In a counting problem, it often equals 1.
Choosing a Split Point
The split-point recurrence tries every place k where [i, j] can divide into [i, k] and [k+1, j]:
dp[i][j] = min over i <= k < j of dp[i][k] + dp[k+1][j] + cost(i, k, j)
Here cost(i, k, j) is the price of combining the two halves. Each interval checks up to j - i split points.
Filling the Table by Interval Length
Every subinterval on the right-hand side is strictly shorter than [i, j]. If you fill cells in order of increasing length, every value a cell depends on is already computed when you reach it. Plain row-by-row order does not guarantee this.
def fill_order(n):
order = []
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
order.append((i, j))
return order
print(fill_order(4))
# [(0, 1), (1, 2), (2, 3), (0, 2), (1, 3), (0, 3)]Exercise
You fill the table with "for i in range(n): for j in range(i + 1, n):". Why can dp[0][2] be wrong?
Show answer
When you compute dp[0][2] (row 0), dp[1][2] from row 1 has not been filled yet. The split k = 0 then reads a value that was never computed. Iterating by length, or with i descending, fixes this.