Sub topic 1
Thinking in Intervals: What dp[i][j] Means
Many optimization problems on sequences have the same structure. The best answer for the whole sequence comes from the best answers for its contiguous pieces. Interval dynamic programming is the technique that uses this structure. Its state, dp[i][j], stores the answer to the original problem restricted to one contiguous range of the input.
This chapter covers what that state means, how to choose its bounds, and how to tell whether a problem fits the pattern. Later chapters cover base cases, recurrences, and fill order in detail. The goal here is to give you a precise mental model before any recurrence is written.
Prerequisites
This chapter assumes you are comfortable with:
- Basic dynamic programming: memoization (top-down caching) and tabulation (bottom-up table filling)
- Recursion and how a recursive function breaks a problem into subproblems
- Two-dimensional arrays (lists of lists in Python)
- Big-O notation for time and space
- Reading Python code, including slicing such as
seq[i:j]
You do not need to have seen interval DP before.
From prefixes to ranges
Most introductory DP problems use a one-dimensional state over prefixes. In longest increasing subsequence or coin change, dp[i] describes the first i elements or the amount i. The subproblems grow in one direction only.
Interval DP needs two indices because its subproblems can be cut from either side. Suppose you must decide how to multiply a chain of matrices, or which pair of adjacent piles to merge first. Once you commit to a choice in the middle of the sequence, you are left with a left piece and a right piece. Neither piece is a prefix in general. The right piece of A1 A2 A3 A4 split after A2 is A3 A4, and a prefix-only state cannot describe it.
So the state names both ends:
dp[i][j]= the optimal answer to the original problem, applied only to the elements from positionito positionj.
The answer to the full problem is then the entry covering the whole sequence, usually dp[0][n - 1].
Writing the meaning sentence
Before you write any code, write one sentence that defines the state. That sentence should be complete enough that someone else could compute any single entry by brute force. Here are three examples from problems later in this tutorial:
- Matrix chain:
dp[i][j]is the minimum number of scalar multiplications needed to compute the productA_i · A_{i+1} · … · A_j. - Longest palindromic subsequence:
dp[i][j]is the length of the longest palindromic subsequence ofs[i..j], inclusive on both ends. - Stone merging:
dp[i][j]is the minimum total cost to merge pilesithroughjinto a single pile.
Each sentence has the same three parts: what is being optimized, the operation, and the exact range. If you cannot write this sentence, you cannot debug the recurrence, because you have no way to check whether a single cell is correct.
Choosing bounds: inclusive, half-open, or open
The meaning sentence must say exactly which endpoints are included. Mixing conventions is the most common source of off-by-one bugs in interval DP. Three conventions appear in practice.
| Convention | Range covered by `dp[i][j]` | Python slice | Empty interval | Full answer |
|---|---|---|---|---|
| Inclusive `[i, j]` | elements `i` through `j` | `seq[i:j+1]` | `j = i - 1` (usually not stored) | `dp[0][n-1]` |
| Half-open `[i, j)` | elements `i` through `j - 1` | `seq[i:j]` | `i == j` | `dp[0][n]` |
| Open `(i, j)` | elements strictly between `i` and `j` | `seq[i+1:j]` | `j == i + 1` | `dp[0][n+1]` on a padded array |
Inclusive bounds read naturally when every useful interval has at least one element, as in matrix chain and palindromes. Half-open bounds make the empty interval a normal cell and match Python slicing, which helps when empty ranges carry meaning. Open bounds are useful when the endpoints act as fixed neighbors that are not themselves part of the subproblem. Burst balloons uses this convention, and a later chapter explains why.
Any of the three is correct if you use it consistently. Pick one, write it into the meaning sentence, and check every index in the recurrence against it.
What the table looks like
With inclusive bounds on a sequence of length n, only cells with i <= j mean anything. They form the upper triangle of an n × n grid, including the diagonal. The diagonal holds single-element intervals. Each step to the right adds one element to the interval, and the top-right corner is the whole sequence.
The code below lists the valid states under both inclusive and half-open bounds and draws the triangle.
def interval_states(n, half_open=False):
"""Return every non-empty contiguous interval of a length-n sequence."""
states = []
for i in range(n):
for j in range(i, n):
states.append((i, j + 1) if half_open else (i, j))
return states
n = 4
closed = interval_states(n)
print(len(closed)) # 10, which is n * (n + 1) // 2
print(closed[:4]) # [(0, 0), (0, 1), (0, 2), (0, 3)]
print(interval_states(n, True)[:4]) # [(0, 1), (0, 2), (0, 3), (0, 4)]
seq = ["A", "B", "C", "D"]
i, j = 1, 2
print(seq[i:j + 1]) # ['B', 'C']: inclusive [1, 2]
for r in range(n):
print(" ".join("." if c < r else "#" for c in range(n)))
# # # # #
# . # # #
# . . # #
# . . . #The count n(n + 1) / 2 matters. A sequence has O(n²) contiguous intervals, so interval DP has O(n²) states. Compare that with the 2ⁿ subsets a brute-force search over choices might visit. The O(n²) state count, multiplied by the work per state, determines the running time, which the complexity chapter covers in full.
Recognizing an interval problem
A problem fits interval DP when these properties hold together:
- The order is fixed. The input is a sequence, and you may not reorder it. Only adjacent elements, or adjacent groups, combine.
- A choice splits the range into independent pieces. After you fix one decision inside
[i, j], such as a split point, a matched pair of endpoints, or the last operation, the remaining work falls into smaller contiguous ranges that do not affect each other. - The answer for a range depends only on that range. Nothing outside
[i, j]changes the best value inside it. Sometimes you get this property by putting the right boundary information into the state. - Greedy choices fail. Taking the locally cheapest merge or multiplication first does not give the global optimum. This is why every option has to be considered.
Typical signals in a problem statement are "adjacent", "merge neighboring", "parenthesize", "substring" or "subsequence of a string read from both ends", and "remove an element and its neighbors join".
Some problems look similar but do not fit. The 0/1 knapsack problem picks an arbitrary subset, so contiguity means nothing and the state is (item index, capacity). Problems where any two elements can be combined regardless of position, such as merging piles with no adjacency rule, are usually solved greedily with a heap. In those problems the ordering of the sequence carries no structure.
Common mistakes in defining the state
- Vague meaning. "dp[i][j] is the answer for i and j" cannot be checked. State the operation, the objective, and the bounds.
- Mixed bounds. The meaning sentence says inclusive, but the recurrence reads
dp[k][j]anddp[k][j]for both halves, which counts elementktwice. With inclusive bounds the halves are[i, k]and[k + 1, j]. - Reading the answer from the wrong cell. With inclusive bounds the answer is
dp[0][n - 1], and with half-open bounds it isdp[0][n]. Readingdp[0][n]from an inclusiven × ntable raises anIndexError. - A state that leaks outside the range. In burst balloons, the value of popping a balloon depends on its current neighbors, which may lie outside
[i, j]. A plain inclusive state then breaks property 3. The fix changes what the state means: it uses open bounds, so the endpoints are the known neighbors. - Assuming lower-triangle cells are zero. Cells with
i > jare not defined unless you deliberately treat them as the empty interval. Reading one by accident can return a plausible-looking 0 and hide the bug.
Exercise
You are given a string s of length n and must find the minimum number of characters to insert so that s becomes a palindrome. Write a precise meaning sentence for dp[i][j] using inclusive bounds, state which cell holds the final answer, and give the Python slice that dp[i][j] describes.
Show answer
dp[i][j] is the minimum number of insertions needed to make the substring s[i..j], inclusive on both ends, a palindrome. The final answer is dp[0][n - 1]. The cell describes s[i:j + 1].
Exercise
A colleague defines dp[i][j] as "the minimum cost to merge piles i through j" using half-open bounds, so dp[i][j] covers piles i to j - 1. Their recurrence for a split at k combines dp[i][k] and dp[k + 1][j]. What is wrong, and what should the two halves be?
Show answer
With half-open bounds, dp[i][k] covers piles i to k - 1 and dp[k + 1][j] covers piles k + 1 to j - 1, so pile k belongs to neither half. The halves should be dp[i][k] and dp[k][j], with i < k < j, so that every pile is covered exactly once.
Exercise
How many valid states does an inclusive-bounds interval DP have for n = 100, and why is this better than enumerating every way of grouping the elements?
Show answer
There are n(n + 1)/2 = 100 · 101 / 2 = 5050 states. The number of ways to group or parenthesize the elements grows exponentially (it follows the Catalan numbers), but every grouping is built from the same O(n²) contiguous intervals. Each interval is solved once and reused.