Longest Palindromic Subsequence (LeetCode 516): Solution and Explanation
Given a string s, find the length of the longest subsequence that reads the same forward and backward. A subsequence keeps the original order of characters but may skip any of them, so the palindrome does not have to be contiguous.
Watch it run step by step
Try your own input and write the code →Intuition
Brute force would generate all 2^n subsequences and test each one for being a palindrome, which is hopeless beyond about 20 characters. We need to reuse work, and the natural place to look is the two ends of the string.
Look at the first and last characters of some substring s[i..j]. If they match, they can be the outer pair of a palindrome, and the best answer is 2 plus the best palindrome strictly inside, s[i+1..j-1]. If they differ, at least one of them cannot be in the answer, so the best is whichever is larger: drop the left end and solve s[i+1..j], or drop the right end and solve s[i..j-1]. That is a complete recurrence over substrings.
Each state depends only on shorter substrings, so filling the table by increasing length guarantees every value you read is already computed. Single characters form the base case, since any one character is a palindrome of length 1. The answer for the whole string sits in dp[0][n-1].
Approach: Interval dynamic programming
- Create an n by n table
dpof zeros, wheredp[i][j]will hold the answer fors[i..j]. - Set
dp[i][i] = 1for every index, since each single character is a palindrome. - Loop
lengthfrom 2 up to n, and for each length loop the startiwith endj = i + length - 1. - If
s[i] == s[j], setdp[i][j] = dp[i+1][j-1] + 2. For length 2 that inner cell lies below the diagonal and is still 0, which is exactly right. - Otherwise set
dp[i][j] = max(dp[i+1][j], dp[i][j-1]). - Return
dp[0][n-1].
Step-by-step example
s = "bbbab"
- The diagonal is all 1s. For length 2:
"bb"at (0,1) and (1,2) gives 2, while"ba"at (2,3) and"ab"at (3,4) give 1. - Length 3: (0,2) is
"bbb", ends match, sodp[1][1] + 2 = 3. (1,3) is"bba", ends differ, somax(dp[2][3], dp[1][2]) = 2. (2,4) is"bab", ends match, sodp[3][3] + 2 = 3. - Length 4: (0,3) is
"bbba", ends differ, givingmax(dp[1][3], dp[0][2]) = max(2, 3) = 3. (1,4) is"bbab", ends match, givingdp[2][3] + 2 = 3. - Length 5: (0,4) has matching ends, so
dp[1][3] + 2 = 2 + 2 = 4. - The function returns 4, which corresponds to the subsequence
"bbbb".
Code: Python, Java, C++
1class Solution:
2 def longestPalindromeSubseq(self, s: str) -> int:
3 n = len(s)
4 dp = [[0] * n for _ in range(n)]
5
6 # Base case: single characters are palindromes
7 for i in range(n):
8 dp[i][i] = 1
9
10 # Fill table for increasing lengths
11 for length in range(2, n + 1):
12 for i in range(n - length + 1):
13 j = i + length - 1
14 if s[i] == s[j]:
15 dp[i][j] = dp[i+1][j-1] + 2
16 else:
17 dp[i][j] = max(dp[i+1][j], dp[i][j-1])
18
19 return dp[0][n-1]1class Solution {
2 public int longestPalindromeSubseq(String s) {
3 int n = s.length();
4 int[][] dp = new int[n][n];
5
6 for (int i = 0; i < n; i++) dp[i][i] = 1;
7
8 for (int len = 2; len <= n; len++) {
9 for (int i = 0; i <= n - len; i++) {
10 int j = i + len - 1;
11 if (s.charAt(i) == s.charAt(j)) {
12 dp[i][j] = dp[i+1][j-1] + 2;
13 } else {
14 dp[i][j] = Math.max(dp[i+1][j], dp[i][j-1]);
15 }
16 }
17 }
18
19 return dp[0][n-1];
20 }
21}1class Solution {
2public:
3 int longestPalindromeSubseq(string s) {
4 int n = s.size();
5 vector<vector<int>> dp(n, vector<int>(n, 0));
6
7 for (int i = 0; i < n; i++) dp[i][i] = 1;
8
9 for (int len = 2; len <= n; len++) {
10 for (int i = 0; i <= n - len; i++) {
11 int j = i + len - 1;
12 if (s[i] == s[j]) {
13 dp[i][j] = dp[i+1][j-1] + 2;
14 } else {
15 dp[i][j] = max(dp[i+1][j], dp[i][j-1]);
16 }
17 }
18 }
19
20 return dp[0][n-1];
21 }
22};Time and space complexity
O(n²)
There are about n²/2 substring states and each is filled in constant time from three neighbors.
O(n²)
The full n by n table is stored. Only the upper triangle is actually used.
Other approaches
LCS with the reversed string (time O(n²), space O(n²), or O(n) with rolling rows)
The answer equals the longest common subsequence of s and s[::-1]. It reuses a familiar DP and has the same cost, but the interval recurrence above is more direct.
Space-optimized 1D DP (time O(n²), space O(n))
Iterate i from n-1 down to 0 and j from i+1 up, keeping only the row for i+1 and the current row. It cuts memory to linear while keeping the same recurrence.
Common mistakes
- Confusing this with longest palindromic substring. A subsequence can skip characters, so
"bbbab"has answer 4 here, but its longest contiguous palindrome has length 3. - Filling the table row by row from the top.
dp[i][j]needs values from rowi+1, so you must go by increasing length or iterateidownward. - Adding 2 when the ends match but forgetting the length 2 case. If the base cells below the diagonal are not zero,
"aa"will come out wrong. - Taking
maxof all three neighbors even when the ends match. It still works, but addingdp[i+1][j-1] + 2is the correct and sufficient choice when they match.
Frequently asked questions
What is the difference between longest palindromic subsequence and substring?
A substring must be contiguous, while a subsequence may skip characters as long as the order stays the same. That is why the subsequence version uses a max over two shrunk intervals when the ends differ.
Why fill the DP table by length?
Each dp[i][j] depends on intervals that are one or two characters shorter. Processing lengths from 2 up to n guarantees those values are ready when needed.
Can it be solved using LCS?
Yes. The longest palindromic subsequence of s is the longest common subsequence of s and its reverse, which also runs in O(n²) time.
Can the space be reduced below O(n²)?
Yes. Each row only depends on the row below it, so keeping two one-dimensional arrays brings memory down to O(n).