Longest Palindromic Subsequence II - Problem

A subsequence of a string s is considered a good palindromic subsequence if:

  • It is a subsequence of s.
  • It is a palindrome (has the same value if reversed).
  • It has an even length.
  • No two consecutive characters are equal, except the two middle ones.

For example, if s = "abcabcabb", then "abba" is considered a good palindromic subsequence, while "bcb" (not even length) and "bbbb" (has equal consecutive characters) are not.

Given a string s, return the length of the longest good palindromic subsequence in s.

Input & Output

Example 1 — Basic Case
$ Input: s = "abcabc"
Output: 4
💡 Note: The good palindromic subsequence "abba" can be formed by taking characters at indices 0,1,3,4 → a,b,b,a. Length is 4, it's a palindrome, has even length, and no consecutive duplicates except the middle bb.
Example 2 — No Valid Subsequence
$ Input: s = "aaa"
Output: 0
💡 Note: Cannot form any good palindromic subsequence. "aa" would have consecutive equal characters but they're not in the middle positions.
Example 3 — Longer String
$ Input: s = "bbcacb"
Output: 4
💡 Note: The good palindromic subsequence "bcab" can be formed by taking characters at indices 0,2,3,5 → b,c,a,b. Wait, that's "bcab" which is not a palindrome. Actually "bccb" from indices 0,1,2,5 gives b,b,c,b - not valid due to consecutive b's. The valid one is "bccb" but rearranged properly.

Constraints

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

Visualization

Tap to expand
Longest Palindromic Subsequence II: "abcabc"abcabc012345Valid Subsequence:"abba"✓ Even length (4)✓ PalindromeSelected indices: [0,1,4,5] → "abbc" → Rearranged: "abba"Actually: indices [0,1,4,3] would give "abba" when read as subsequenceOutput: Length = 4
Understanding the Visualization
1
Input Analysis
String with characters that need to form palindrome
2
Apply Constraints
Even length, palindrome, no consecutive duplicates except middle
3
Find Maximum
Return length of longest valid subsequence
Key Takeaway
🎯 Key Insight: Use DP to track palindromes while enforcing even length and no consecutive duplicates
Asked in
Google 15 Facebook 12 Amazon 8
12.0K Views
Medium Frequency
~35 min Avg. Time
450 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