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 INPUT String s: b 0 b 1 b 2 a 3 b 4 s = "bbbab" length = 5 Subsequence: derived by deleting some elements keeping order Palindrome: reads same forwards and backwards ALGORITHM (DP) 1 Create DP Table dp[i][j] = LPS length from index i to j 2 Base Case dp[i][i] = 1 (single char) 3 Fill DP Table If s[i]==s[j]: dp[i][j]= dp[i+1][j-1] + 2 4 Otherwise dp[i][j] = max(dp[i+1][j], dp[i][j-1]) DP Table (partial): b b b a b b 1 2 3 3 4 b 1 2 2 3 Answer: dp[0][n-1] FINAL RESULT Longest Palindromic Subsequence: b b b b "bbbb" From original string: b b b a b (skip 'a' at index 3) Output: 4 [OK] Verified: "bbbb" is a palindrome of length 4 Key Insight: The LPS problem has optimal substructure: if s[i] == s[j], the LPS includes both characters plus the LPS of substring s[i+1..j-1]. Otherwise, we take max of excluding either endpoint. Time Complexity: O(n^2) | Space Complexity: O(n^2) using 2D DP table TutorialsPoint - Longest Palindromic Subsequence | Dynamic Programming Approach
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