Sub topic 8
Worked Example: Longest Palindromic Subsequence
This chapter applies the endpoint-shrinking recurrence from the previous chapter to a full problem. It assumes you can read Python, are comfortable with 2D lists, and know what dp[i][j] means for an inclusive interval. You will build the table, check it by hand, recover an actual palindrome from it, cut memory to O(n), and see which related problems reduce to it.
The Problem
A subsequence keeps some characters of a string in their original order, possibly with gaps. A palindrome reads the same forwards and backwards. Given a string s, the task is to find the length of its longest subsequence that is a palindrome.
For "bbbab" the answer is 4, from "bbbb". The a is skipped. For "cbbd" the answer is 2, from "bb".
Defining the State
Let dp[i][j] be the length of the longest palindromic subsequence of s[i..j], with both ends inclusive.
- The answer is
dp[0][n-1]. - A single character is a palindrome of length 1, so
dp[i][i] = 1. - An empty interval (
i > j) has length 0. We never store these cells on purpose, but the recurrence reads one of them, as shown below.
The Recurrence
Look at the two end characters s[i] and s[j] with i < j.
- Ends match (
s[i] == s[j]): both characters can wrap whatever palindrome lives strictly inside. Sodp[i][j] = dp[i+1][j-1] + 2. - Ends differ: at least one end cannot be in the palindrome. If both were used, the first and last characters of the palindrome would differ. Drop one end and take the better result:
dp[i][j] = max(dp[i+1][j], dp[i][j-1]).
The matching case has no max over alternatives, and that needs a short argument. Suppose some optimal palindrome for s[i..j] does not use both s[i] and s[j]. Its outer characters can then be replaced by s[i] and s[j] (or, if it skips one of them, that one can be added at its end) without making it shorter. So using both matched ends is always at least as good, and comparing against the "drop one end" options is unnecessary.
The empty-interval edge case
When j == i + 1 and the two characters match, the recurrence reads dp[i+1][i], which is an empty interval. It must equal 0. With a table initialized to zeros, every cell below the diagonal is 0, so this works without a special branch. If you initialize the table with -1 or None for memoization, you must handle i > j explicitly. Forgetting to do so is a frequent bug.
Evaluation Order
Cell (i, j) reads row i+1 and column j-1 of row i. Iterating i from n-1 down to 0, and j from i+1 up to n-1 inside that, guarantees both are ready. This bottom-to-top, left-to-right sweep is equivalent to filling by increasing interval length, since every dependency is a strictly shorter interval. Either order is correct. The row sweep is just simpler to write.
def longest_palindromic_subsequence(s):
n = len(s)
if n == 0:
return 0
dp = [[0] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
dp[i][i] = 1
for j in range(i + 1, n):
if s[i] == s[j]:
dp[i][j] = dp[i + 1][j - 1] + 2
else:
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
return dp[0][n - 1]
print(longest_palindromic_subsequence("bbbab")) # 4If you iterate i upward instead, dp[i+1][...] is still zero when you read it, and the function silently returns wrong answers. It does not crash, so this mistake can go unnoticed.
Tracing the Table for "bbbab"
Indices are 0:b 1:b 2:b 3:a 4:b. Rows are i, columns are j. A dot marks an empty interval that holds 0.
| i \ j | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| 0 | 1 | 2 | 3 | 3 | 4 |
| 1 | · | 1 | 2 | 2 | 3 |
| 2 | · | · | 1 | 1 | 3 |
| 3 | · | · | · | 1 | 1 |
| 4 | · | · | · | · | 1 |
A few cells worked by hand:
dp[1][2]:b == b, sodp[2][1] + 2 = 0 + 2 = 2. This is the empty-interval case.dp[1][3]:b != a, somax(dp[2][3], dp[1][2]) = max(1, 2) = 2.dp[0][4]:b == b, sodp[1][3] + 2 = 4.
Recovering the Palindrome
The table stores lengths only, but you can walk it from (0, n-1) to rebuild one optimal subsequence. At each step, repeat the decision the recurrence made.
def lps_string(s):
n = len(s)
if n == 0:
return ""
dp = [[0] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
dp[i][i] = 1
for j in range(i + 1, n):
if s[i] == s[j]:
dp[i][j] = dp[i + 1][j - 1] + 2
else:
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
left = []
middle = ""
i, j = 0, n - 1
while i <= j:
if i == j:
middle = s[i]
break
if s[i] == s[j]:
left.append(s[i])
i += 1
j -= 1
elif dp[i + 1][j] >= dp[i][j - 1]:
i += 1
else:
j -= 1
return "".join(left) + middle + "".join(reversed(left))
print(lps_string("bbbab")) # bbbb
print(lps_string("character")) # caracMatched ends go into left, and their mirror goes on the right. If the walk ends on a single cell, that character becomes the odd middle. The walk takes O(n) steps because each step shrinks the interval. Ties in the >= comparison pick one of several equally long answers. Change the tie rule if you need a specific one, such as the lexicographically smallest, but be aware that the lexicographic version needs more care than flipping the comparison.
Reducing Space to O(n)
Row i reads only row i+1 and itself, so two 1D arrays are enough when you need the length and not the reconstruction.
def lps_length_linear_space(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 # row i
cur[i] = 1
for j in range(i + 1, n):
if s[i] == s[j]:
cur[j] = prev[j - 1] + 2
else:
cur[j] = max(prev[j], cur[j - 1])
prev = cur
return prev[n - 1]
print(lps_length_linear_space("bbbab")) # 4
print(lps_length_linear_space("cbbd")) # 2The empty-interval read prev[i] (that is, dp[i+1][i]) is still 0, because each fresh cur row is zero to the left of its diagonal. Once you drop the full table, you lose the ability to walk back through it, which is the usual trade-off with rolling arrays.
Related Problems That Reduce to This One
| Problem | Reduction |
|---|---|
| Minimum insertions to make `s` a palindrome | `n - LPS(s)`. Each character outside the palindrome needs one mirrored partner. |
| Minimum deletions to make `s` a palindrome | Also `n - LPS(s)`. |
| Is `s` a "k-palindrome" (palindrome after at most k deletions)? | Check `n - LPS(s) <= k`. |
| LPS through LCS | `LPS(s) == LCS(s, reversed(s))`. This is the same O(n²) cost from a different angle. |
The LCS view (LCS is the longest common subsequence) is a useful cross-check in tests. The interval form is usually preferred, because the same table directly answers the question for every substring s[i..j], which the LCS table does not do.
Common Errors
- Iterating
iupward, so rowi+1has not been computed when it is read. - Initializing a memo table with a sentinel and then reading
dp[i+1][i]as if it were 0. - Writing
dp[i+1][j-1] + 1in the match case. Two characters are added, not one. - Adding a third option
dp[i+1][j-1]to the mismatchmax. It is never larger than the other two, so it is harmless but unnecessary, and it suggests the recurrence has been misunderstood. - Solving the substring problem by accident: a substring recurrence requires
dp[i+1][j-1]to be a full palindrome, which a subsequence does not.
Exercise
What is the minimum number of characters you must insert into "mbadm" to make it a palindrome? Show the LPS you use.
Show answer
The longest palindromic subsequence has length 3, for example "mam" or "mbm" or "mdm". The string has length 5, so the answer is 5 - 3 = 2 insertions (one result is "mbdadbm").
Exercise
In the 2D implementation, change the outer loop to for i in range(n) and keep everything else the same. What does the function return for "bbbab", and why?
Show answer
It returns 2. When row i is computed, row i+1 is still all zeros, so every match case gives 0 + 2 = 2 and every mismatch gives max(0, dp[i][j-1]). The bottom row is never filled before it is read, so no cell can exceed 2.
Exercise
Modify the recurrence so that dp[i][j] counts the number of distinct index sets that form palindromic subsequences of s[i..j] (non-empty, counting the same string at different positions separately). Give the recurrence for the match and mismatch cases.
Show answer
Use inclusion-exclusion. Mismatch: dp[i][j] = dp[i+1][j] + dp[i][j-1] - dp[i+1][j-1]. Match: the same three terms, plus dp[i+1][j-1] + 1 for the new subsequences that use both ends (each inner palindrome wrapped by s[i] and s[j], plus the pair alone). This simplifies to dp[i][j] = dp[i+1][j] + dp[i][j-1] + 1. Base case: dp[i][i] = 1, and empty intervals are 0.