Longest Palindromic Subsequence II - Problem

Given a string s, you need to find the length of the longest "good palindromic subsequence". This is a special type of palindrome with strict rules!

A good palindromic subsequence must satisfy ALL of the following conditions:

  • It is a subsequence of the original string s
  • It reads the same forwards and backwards (palindrome)
  • It has an even length (2, 4, 6, 8, etc.)
  • No two consecutive characters are equal, except the two middle characters

Examples:

  • "abba" - Even length, palindrome, no consecutive duplicates
  • "bcb" - Odd length (not allowed)
  • "bbbb" - Has consecutive equal characters
  • "abccba" - Even length, only middle characters are equal

Your goal is to return the length of the longest such subsequence.

Input & Output

example_1.py — Python
$ Input: s = "bbcacabb"
Output: 4
💡 Note: The longest good palindromic subsequence is "bccb" with length 4. It's even length, palindrome, and only the middle characters 'c','c' are consecutive and equal.
example_2.py — Python
$ Input: s = "aabaa"
Output: 4
💡 Note: The longest good palindromic subsequence is "abba" with length 4. We skip the middle 'a' to avoid three consecutive 'a's in the palindrome.
example_3.py — Python
$ Input: s = "abc"
Output: 0
💡 Note: No valid good palindromic subsequence exists. We need at least 2 matching characters to form an even-length palindrome.

Visualization

Tap to expand
Building Good Palindromic SubsequencesString: "bbcacabb"bbcacabbBuilding ProcessMatch outer 'b'sMatch inner 'c'sbccbResult: "bccb" (length 4)Validation RulesEven length (4)PalindromeNo consecutive duplicates (except cc in middle)
Understanding the Visualization
1
Start from Ends
Begin matching characters from both ends of the string
2
Check Rules
Ensure no consecutive duplicates except middle pair
3
Build Inward
Recursively build the palindrome from outside to inside
4
Memoize Results
Cache results to avoid recomputing same subproblems
Key Takeaway
🎯 Key Insight: Use dynamic programming to match characters from both ends while tracking the last used character to prevent consecutive duplicates, building the longest valid palindromic subsequence efficiently.

Time & Space Complexity

Time Complexity
⏱️
O(n² × 26)

n² possible (left,right) pairs, 26 possible last characters to track

n
2n
Quadratic Growth
Space Complexity
O(n² × 26)

Memoization table for all possible states

n
2n
Quadratic Space

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists only of lowercase English letters
  • The subsequence must have even length
  • No consecutive equal characters except the middle pair
Asked in
Google 42 Amazon 38 Meta 25 Microsoft 18
38.2K Views
Medium Frequency
~25 min Avg. Time
1.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