Palindromic Subsequence DP

Interval DP over a string: dp[i][j] describes the piece from i to j, and matching end characters let you grow a palindrome from the inside out.

Overview

Two words that look alike

A palindrome reads the same forward and backward: 'racecar', 'abba', or a single character. Problems ask about palindromes inside a longer string, and the first thing to settle is which kind.

A substring keeps characters that sit next to each other. A subsequence keeps characters in order but allows gaps. In 'bbbab', 'bbb' is a palindromic substring, while 'bbbb' is a palindromic subsequence, because it skips the 'a'. The gaps make a big difference in scale. A string has about n² substrings but about 2ⁿ subsequences. So the DP stores different things for each. For substrings it stores a yes or no: is s[i..j] a palindrome? For subsequences it stores a number: the best answer for s[i..j].

Both kinds use the same state, dp[i][j] for the piece of the string from index i to index j. That makes them interval DP: a longer piece is answered from shorter pieces inside it.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio