Problem 516 · LeetCode 516(opens in a new tab)
Longest Palindromic Subsequence
MediumDynamic programming
You are given a string s. A subsequence keeps some of the letters of s, possibly all of them, in their original order; letters may be skipped but never rearranged.
Return the length of the longest subsequence of s that is a palindrome, meaning it reads the same from left to right as from right to left.
Example 1
Input: s = "abab" Output: 3 Why: "aba" and "bab" both work; no length-4 one exists
2 more examples and the constraints
Example 2
Input: s = "rtacecar" Output: 7 Why: skip the t to get "racecar"
Example 3
Input: s = "xyz" Output: 1 Why: no two letters match, so one letter is the best
Constraints
- 1 ≤ length of s ≤ 1,000
- s contains only lower-case English letters
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursion with memoO(n²)
- Bottom-up interval tableO(n²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 1,000 letters | Verdict |
|---|---|---|---|
| Recursion with memo | O(n²) | Passes; deep recursion | |
| Bottom-up interval table | O(n²) | Best; no recursion |
n = length of s. Both fill the same n² / 2 cells; the table skips the call overhead.
Edge cases to test
- One letter. "q" gives 1.
- All letters different. "xyz" gives 1: a single letter is always a palindrome.
- All letters the same. "aaaa" gives 4, the whole string.
- Already a palindrome. "level" gives 5.
Common mistakes
- Confusing a subsequence with a substring: letters may be skipped here.
- Filling the table with i going up, so dp[i + 1][...] is read before it is filled.
- When the ends match, forgetting the inside is empty for two adjacent letters, so "bb" should give 2.
How to talk through it
- 1Clarify. Subsequence, not substring? Return only the length, not the palindrome itself?
- 2Rule out brute force. There are 2ⁿ subsequences; for 1,000 letters that is out of the question.
- 3State the recurrence. Matching ends: inside + 2. Different ends: the better of dropping either one.
- 4Pick a fill order. i from the end backwards, j forwards, so every needed cell is ready.
- 5Test out loud. Run "abab", a single letter and "bb" through the table.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?