Longest Palindromic Subsequence - Problem

Given a string s, find the longest palindromic subsequence's length in s.

A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

For example, "ace" is a subsequence of "aec" (by removing 'e'), but "aec" is not a subsequence of "ace".

Input & Output

Example 1 — Basic Case
$ Input: s = "bbbab"
Output: 4
💡 Note: One possible longest palindromic subsequence is "bbbb" (indices 0,1,2,4). We can also form "bbb" of length 3, but "bbbb" is longer.
Example 2 — All Different Characters
$ Input: s = "cbbd"
Output: 2
💡 Note: One possible longest palindromic subsequence is "bb" (indices 1,2). Each single character is also a palindrome of length 1.
Example 3 — Single Character
$ Input: s = "a"
Output: 1
💡 Note: The entire string "a" is a palindrome, so the longest palindromic subsequence has length 1.

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists only of lowercase English letters

Visualization

Tap to expand
Longest Palindromic Subsequence: "bbbab"Input String:bbbab01234Possible Subsequences:bbbb"bbbb" - Length 4 ✓ Palindromebab"bab" - Length 3 ✓ PalindromeAnswer: 4 (longest palindromic subsequence)
Understanding the Visualization
1
Input
String "bbbab" - find longest palindromic subsequence
2
Process
Use DP to build solution from smaller substrings
3
Output
Length of longest palindromic subsequence
Key Takeaway
🎯 Key Insight: Build the solution by comparing characters at both ends and solving subproblems optimally
Asked in
Amazon 45 Google 38 Microsoft 32 Facebook 28
85.0K Views
High Frequency
~25 min Avg. Time
4.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen