Sub topic 2
Base Cases: Empty and Single-Element Ranges
This chapter assumes you already know basic dynamic programming (memoization and tabulation), recursion, and Python's two-dimensional lists. It also assumes you have read the previous chapter, which defined the interval state dp[i][j] over a contiguous range. Recurrences, fill order, and the full worked examples come in later chapters. Here the focus is narrower: the smallest intervals, what values they hold, and how wrong base cases quietly break an otherwise correct solution.
Why the Smallest Intervals Matter
Every interval recurrence builds a range from shorter ranges. When you follow that chain far enough, you reach ranges that cannot be split or shrunk any further. Those ranges have no subproblems, so their values cannot come from the recurrence. You must define them directly.
Interval DP has two kinds of smallest range:
- Single-element ranges hold exactly one item, such as one matrix, one character, or one pile.
- Empty ranges hold no items. They show up when a recurrence drops both endpoints of a two-element range, or when a split leaves nothing on one side.
Many bugs in interval DP come from one of three mistakes. The code gives a base case the wrong value. It treats an empty range as if it cannot occur. Or it reads an index that Python silently wraps around.
Where Empty and Single Ranges Live in Each Bound Convention
Whether a range is empty depends on how you defined the bounds. The previous chapter stressed choosing inclusive or exclusive bounds precisely, and this is where that choice starts to matter.
| Convention | Meaning of `(i, j)` | Empty range | Single element |
|---|---|---|---|
| Inclusive `[i, j]` | items i through j | `i > j` (usually `i == j + 1`) | `i == j` |
| Half-open `[i, j)` | items i through j − 1 | `i == j` | `j == i + 1` |
| Open `(l, r)` | items strictly between l and r | `r == l + 1` | `r == l + 2` |
Matrix chain multiplication and palindromic subsequences usually use inclusive bounds. Burst balloons uses open bounds, with sentinel balloons at both ends. If you mix conventions inside one solution, your base cases will land in the wrong cells.
Choosing the Right Base Value
A base value is not arbitrary. It must be the true answer to the subproblem it represents, and it must combine correctly with the operation in your recurrence. A useful check is to ask: "If this range really had zero or one item, what would the answer be?"
| Problem | Single element | Empty range | Reason |
|---|---|---|---|
| Matrix chain (min cost) | 0 | not reached | One matrix needs no multiplication |
| Longest palindromic subsequence | 1 | 0 | One character is a palindrome of length 1 |
| Is `s[i..j]` a palindrome? | True | True | The empty string is a palindrome |
| Stone merging (min cost) | 0 | not reached | One pile needs no merge |
| Burst balloons (max coins) | value of one burst | 0 | No balloons, no coins |
| Count of parenthesizations | 1 | 1 (if used) | There is exactly one way to do nothing |
Three patterns appear in this table:
- Sums of costs use 0 for ranges that need no work, because 0 is the identity for addition.
- Counting problems use 1 for the empty case, because the counts get multiplied and 1 is the identity for multiplication.
- Boolean feasibility uses True for the empty case when an empty structure satisfies the property.
Gotcha 1: Initializing Everything to Infinity
The mistake is easy to make in minimization problems. The code below has a correct recurrence but initializes the table badly.
def matrix_chain_bad(dims):
n = len(dims) - 1
INF = float("inf")
dp = [[INF] * n for _ in range(n)] # bug: diagonal should be 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):
cost = dp[i][k] + dp[k + 1][j] + dims[i] * dims[k + 1] * dims[j + 1]
dp[i][j] = min(dp[i][j], cost)
return dp[0][n - 1]
def matrix_chain_good(dims):
n = len(dims) - 1
INF = float("inf")
dp = [[0] * n for _ in range(n)] # diagonal is 0: a single matrix costs nothing
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
dp[i][j] = INF # placeholder only for cells the recurrence will fill
for k in range(i, j):
cost = dp[i][k] + dp[k + 1][j] + dims[i] * dims[k + 1] * dims[j + 1]
dp[i][j] = min(dp[i][j], cost)
return dp[0][n - 1]
print(matrix_chain_bad([10, 30, 5, 60])) # inf
print(matrix_chain_good([10, 30, 5, 60])) # 4500Every length-2 cell reads two diagonal cells. With infinite diagonals, every length-2 cell becomes infinite, and so does everything built from them. The safe pattern sets the placeholder inside the loop, right before the cell is computed.
Gotcha 2: The Hidden Empty Range in Endpoint Shrinking
Endpoint-shrinking recurrences, covered in detail later, compare s[i] with s[j] and recurse on dp[i + 1][j - 1]. When j == i + 1, that read is dp[i + 1][i], which is an empty range. Your code reaches it even though no loop ever "fills" it.
Code built on a zero-filled table works, because cells below the diagonal stay 0 and 0 is the correct empty value. That correctness is accidental, though. It breaks if you start the table at a different value or switch to a problem whose empty value is not 0. A clearer approach puts the rule in one helper:
def longest_palindromic_subsequence(s):
n = len(s)
dp = [[0] * n for _ in range(n)]
def get(i, j):
# Inclusive bounds: i > j is the empty range.
if i > j:
return 0
return dp[i][j]
for i in range(n - 1, -1, -1):
dp[i][i] = 1 # single character
for j in range(i + 1, n):
if s[i] == s[j]:
dp[i][j] = get(i + 1, j - 1) + 2
else:
dp[i][j] = max(get(i + 1, j), get(i, j - 1))
return get(0, n - 1)
print(longest_palindromic_subsequence("aa")) # 2
print(longest_palindromic_subsequence("bbbab")) # 4
print(longest_palindromic_subsequence("")) # 0For "aa", the length-2 cell reads get(1, 0), which returns 0, so the answer is 2. For the empty string, get(0, -1) returns 0 without touching the table, so the empty input is handled too.
Gotcha 3: Negative Indices Wrap Silently
Python reads dp[i][-1] as the last column instead of raising an error. If a recurrence ever computes j - 1 when j == 0, or i - 1 when i == 0, it reads a real cell from the other end of the table and returns a plausible wrong number. The bounds check in a helper like get blocks this. In languages that check array bounds you get a crash instead, which is easier to debug but still a bug.
Open Bounds Make Empty Ranges Natural
With open intervals, the base case often needs no special code. In the burst balloons formulation, best(left, right) covers the balloons strictly between left and right. When right == left + 1, the loop for k in range(left + 1, right) runs zero times and the function returns its starting value of 0. The empty range handles itself.
This is a real reason to pick open or half-open bounds in some problems. The convention that makes empty ranges fall out of the loop structure tends to produce fewer base-case bugs. The trade-off is that the indices move further from the problem statement, so you need a clear comment explaining what left and right mean.
Inputs of Length Zero and One
Test the base cases at the level of the whole input, not only inside the table:
- n = 0. Allocating
[[0] * 0 for _ in range(0)]gives an empty list, anddp[0][n - 1]fails. Return early or use a guarded accessor. - n = 1. The length loop
range(2, n + 1)does not run, so the answer is the single-element base value. Check that this value really is the answer to the full problem. - Matrix chain with
len(dims) == 1. That input contains zero matrices. Decide whether it is invalid input or costs 0, and document the choice.
A short set of assertions on tiny inputs catches most base-case errors before you test larger cases.
def check_lps():
cases = {"": 0, "a": 1, "ab": 1, "aa": 2, "aba": 3}
for s, expected in cases.items():
assert longest_palindromic_subsequence(s) == expected, s
print("all base-case checks passed")
check_lps()Put this snippet after the longest_palindromic_subsequence definition above and run it. Each case exercises a different base path: the empty input, a single cell, a length-2 mismatch, the hidden empty range, and a length-3 match around a center character.
Exercise
You write a DP that counts the number of ways to fully parenthesize matrices i..j (inclusive), using ways[i][j] = sum over k of ways[i][k] * ways[k+1][j]. You fill the table with zeros and loop over lengths 2 and up. What does ways[0][n-1] return for n >= 2, and what is the fix?
Show answer
It returns 0. Every length-2 cell multiplies two diagonal cells that are 0, so every product is 0 and the zeros spread upward. The single-element base case must be ways[i][i] = 1, because there is exactly one way to "parenthesize" a single matrix. Counting problems need the multiplicative identity 1 in their base cases.
Exercise
A table ispal[i][j] (inclusive bounds) records whether s[i..j] is a palindrome, using ispal[i][j] = (s[i] == s[j]) and ispal[i+1][j-1]. The table starts as all False and the code sets only ispal[i][i] = True. Which strings get wrong answers, and why?
Show answer
Every even-length palindrome, starting with "aa". For j == i + 1, the recurrence reads is_pal[i+1][i], an empty range that is still False, so "aa" is reported as not a palindrome. Longer even-length palindromes depend on that result and fail too. The empty range must count as True, either by starting the table as True or by using an accessor that returns True when i > j.
Exercise
Under the half-open convention [i, j), write the conditions for an empty range and a single-element range, and say which cell holds the answer for a sequence of length n.
Show answer
The range is empty when i == j and holds a single element when j == i + 1. The answer for the full sequence is in dp[0][n], so the table needs n + 1 columns.