DP on strings: palindromes
🌍 In real life. A word game asks for the longest piece of a word that reads the same backwards, a palindrome like "level" or "madam". In "banana" the answer is "anana". Checking every piece letter by letter repeats a lot of work: to know that "anana" is a palindrome you need "nan" to be one, which you have already checked.
The idea in one sentence: let pal[i][j] say whether the piece s[i..j] is a palindrome: it is when its two end letters match and the piece between them is one, so fill the table from short pieces to long, and every piece finds its inside already decided.
Its words:
- palindrome: a piece that reads the same both ways; one letter always is
- interval DP: the state is a stretch
s[i..j], two ends instead of a prefix - fill by length: first every 1-letter piece, then every 2-letter piece, and so on; only half the table (
i <= j) is used
Step by step:
- every one-letter piece is a palindrome: the diagonal is all True
- a two-letter piece is one when its letters match
- a longer piece:
pal[i][j] = s[i] == s[j] and pal[i + 1][j − 1] - the longest True cell is the answer, and the number of True cells counts the palindromes
Watch the table for "banana" fill along its diagonals:
Why short to long. pal[i][j] reads pal[i + 1][j − 1], the piece two letters shorter. Row by row from the top would read a cell that isn't filled yet; by length, it always is.
Letters may also be skipped. The longest palindromic subsequence keeps letters in order but allows gaps: in "bbbab" it is "bbbb", 4 letters, though no 4-letter piece is a palindrome. The same interval table works with numbers: dp[i][j] = dp[i + 1][j − 1] + 2 when the ends match, else max(dp[i + 1][j], dp[i][j − 1]), the LCS rule of Lesson 58.2 applied from both ends.
What it costs, by counting. Half the table: for 1,000 letters, 1,000 × 1,001 / 2 = 500,500 cells, one lookup each. Checking every piece letter by letter instead costs about 1,000 × 1,000 × 1,000 / 6, roughly 166,000,000 comparisons. In Big-O: O(n²) time and O(n²) memory for a word of n letters.
def count_palindromes(s):
n = len(s)
pal = [[False] * n for _ in range(n)] # pal[i][j]: is s[i..j] a palindrome?
count = 0
for length in range(1, n + 1): # short pieces first
for i in range(n - length + 1):
j = i + length - 1
if length == 1:
pal[i][j] = True
elif length == 2:
pal[i][j] = s[i] == s[j]
else:
pal[i][j] = s[i] == s[j] and pal[i + 1][j - 1] # ends match, inside is one
if pal[i][j]:
count += 1
return count
def longest_pal_subseq(s):
n = len(s)
if n == 0:
return 0
dp = [[0] * n for _ in range(n)] # dp[i][j]: the longest palindrome inside s[i..j], gaps allowed
for i in range(n):
dp[i][i] = 1
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
if s[i] == s[j]:
dp[i][j] = dp[i + 1][j - 1] + 2 # both ends wrap the best inside
else:
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]) # drop one end
return dp[0][n - 1]
print(count_palindromes("banana"), count_palindromes("abba"))
print(longest_pal_subseq("bbbab"), longest_pal_subseq("banana"))Mistakes and edge cases.
- filling row by row:
pal[i + 1][j − 1]is on the row below; fill by length, or loop i from the bottom up - two-letter pieces: their inside is empty, so
pal[i + 1][j − 1]would point below the diagonal; handle length 2 on its own - only odd lengths: "abba" has the even palindromes "bb" and "abba"; a count that only grows pieces round a middle letter misses them
- piece or subsequence: a piece (substring) has no gaps; a subsequence may skip letters, so its answer is never shorter
Quiz
Which cell does pal[i][j] need for a piece of 3 or more letters?
- pal[i + 1][j − 1], the piece without its two ends
- pal[i − 1][j + 1]
- pal[i][j − 1]
What does this print?
def count_palindromes(s): n = len(s) pal = [[False] * n for _ in range(n)] # pal[i][j]: is s[i..j] a palindrome? count = 0 for length in range(1, n + 1): # short pieces first for i in range(n - length + 1): j = i + length - 1 if length == 1: pal[i][j] = True elif length == 2: pal[i][j] = s[i] == s[j] else: pal[i][j] = s[i] == s[j] and pal[i + 1][j - 1] # ends match, inside is one if pal[i][j]: count += 1 return count print(count_palindromes("aaa"))What does this print?
def longest_pal_subseq(s): n = len(s) if n == 0: return 0 dp = [[0] * n for _ in range(n)] # dp[i][j]: the longest palindrome inside s[i..j], gaps allowed for i in range(n): dp[i][i] = 1 for length in range(2, n + 1): for i in range(n - length + 1): j = i + length - 1 if s[i] == s[j]: dp[i][j] = dp[i + 1][j - 1] + 2 # both ends wrap the best inside else: dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]) # drop one end return dp[0][n - 1] print(longest_pal_subseq("cbbd"))Why fill the palindrome table by length?
- Each piece reads the piece two letters shorter, which must be ready
- Long pieces are more likely palindromes
- It uses less memory
count_palindromes("abba") gives 4 instead of 6. Which line is wrong?
def count_palindromes(s): n = len(s) pal = [[False] * n for _ in range(n)] count = 0 for length in range(1, n + 1, 2): for i in range(n - length + 1): j = i + length - 1 if length == 1: pal[i][j] = True elif length == 2: pal[i][j] = s[i] == s[j] else: pal[i][j] = s[i] == s[j] and pal[i + 1][j - 1] if pal[i][j]: count += 1 return count
Coding tasks
Write
count_palindromes(s): how many pieces (substrings, counted by position) ofsare palindromes. Every single letter counts.Write
longest_pal_subseq(s): the length of the longest palindrome you can make by deleting letters ofs(keeping the rest in order).