Sub topic 8
Worked Example: Longest Palindromic Subsequence
This chapter assumes you know the endpoint-shrinking recurrence from the previous chapter and can read 2D table code in Python. Here we apply that recurrence to one concrete problem and trace the table by hand.
The Problem
A subsequence keeps characters in their original order but may skip some of them. A palindrome reads the same forwards and backwards. Given a string s, the task is to find the length of its longest palindromic subsequence (LPS).
For "bbbab" the answer is 4, from "bbbb". A substring would have to be contiguous, and the longest palindromic substring here is "bbb", with length 3. Mixing up these two problems is a common error.
State and Recurrence
Let dp[i][j] be the LPS length of s[i..j], with both bounds inclusive. Look at the two endpoints:
- If
s[i] == s[j], both characters can wrap the best palindrome inside them, sodp[i][j] = dp[i+1][j-1] + 2. - Otherwise at least one end is unused, so
dp[i][j] = max(dp[i+1][j], dp[i][j-1]).
The base cases are dp[i][i] = 1 for a single character and 0 for an empty range (i > j).
Implementation
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")) # 4The loop order is a valid alternative to looping by length. With i going downward, row i + 1 is complete before row i starts. With j going upward, dp[i][j - 1] is ready when dp[i][j] needs it.
Tracing "bbbab"
Rows are i and columns are j. Cells with i > j are empty ranges and show as -.
| i \ j | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| 0 (b) | 1 | 2 | 3 | 3 | 4 |
| 1 (b) | - | 1 | 2 | 2 | 3 |
| 2 (b) | - | - | 1 | 1 | 3 |
| 3 (a) | - | - | - | 1 | 1 |
| 4 (b) | - | - | - | - | 1 |
Here is how the final cell is computed. s[0] = 'b' equals s[4] = 'b', so dp[0][4] = dp[1][3] + 2 = 2 + 2 = 4. Now look at dp[0][3], where 'b' and 'a' differ. It takes max(dp[1][3], dp[0][2]) = max(2, 3) = 3.
Common Errors
| Mistake | Symptom |
|---|---|
| Looping `i` upward | Reads `dp[i+1][*]` before it is filled and returns values that are too small |
| Using `dp[i+1][j-1] + 1` on a match | Undercounts, because both endpoints join the palindrome |
| Adding a third option `dp[i+1][j-1]` in the mismatch case | Harmless but redundant, because both `max` options already cover it |
| Solving for contiguous substrings | Wrong problem: substrings need a boolean table instead |
Exercise
Trace the table for "cbbd". What does the function return, and which cell produces the answer?
Show answer
It returns 2. The cell dp[1][2] is 2 because s[1] and s[2] are both 'b', giving dp[2][1] + 2 = 0 + 2. Neither endpoint pair (c,d), (c,b), or (b,d) matches, so the max case carries 2 up to dp[0][3].
Exercise
The fewest insertions that turn s into a palindrome equal len(s) minus its LPS length. Why, and what is the answer for "mbadm"?
Show answer
Every character outside the longest palindromic subsequence needs a mirrored partner inserted, and the characters inside it already pair up. "mbadm" has an LPS of length 3 (for example "mbm"), so it needs 5 - 3 = 2 insertions.