Maximum Product of the Length of Two Palindromic Subsequences - Problem

Given a string s, find two disjoint palindromic subsequences of s such that the product of their lengths is maximized. The two subsequences are disjoint if they do not both pick a character at the same index.

Return the maximum possible product of the lengths of the two palindromic subsequences.

A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string is palindromic if it reads the same forward and backward.

Input & Output

Example 1 — Basic Case
$ Input: s = "leetcodecom"
Output: 9
💡 Note: One optimal solution: subsequence 1 = "ete" (indices 1,2,7), subsequence 2 = "coc" (indices 4,5,10). Both are palindromes with lengths 3 and 3, giving product 3 × 3 = 9.
Example 2 — Short String
$ Input: s = "bb"
Output: 1
💡 Note: The two subsequences must be disjoint, so we can only take one 'b' for each subsequence. Each has length 1, so the product is 1 × 1 = 1.
Example 3 — No Valid Palindromes
$ Input: s = "accbcaxxcxx"
Output: 25
💡 Note: One optimal solution: subsequence 1 = "accca" (indices 0,1,2,4,5), subsequence 2 = "xxcxx" (indices 6,7,8,9,10). Both are palindromes with lengths 5 and 5, giving product 5 × 5 = 25.

Constraints

  • 2 ≤ s.length ≤ 12
  • s consists of lowercase English letters

Visualization

Tap to expand
Maximum Product of Palindromic Subsequences INPUT String s = "leetcodecom" l e e t c o d e c o m 0 1 2 3 4 5 6 7 8 9 Subseq 1 "ete" Subseq 2 "coc" Length 1: 3 (palindrome) Length 2: 3 (palindrome) Constraints: - Subsequences must be disjoint - Both must be palindromes ALGORITHM STEPS 1 Bitmask Enumeration Use masks 1 to 2^n-1 to represent subsequences 2 Check Palindrome For each mask, extract subseq and verify palindrome 3 Check Disjoint Two masks are disjoint if (mask1 AND mask2) == 0 4 Maximize Product Track max(len1 * len2) for all valid pairs Example Masks: mask1: 01001000010 (ete) mask2: 00010100100 (coc) AND: 00000000000 (disjoint!) FINAL RESULT Optimal Palindromes Found: Palindrome 1 "ete" Length: 3 Palindrome 2 "coc" Length: 3 Product Calculation: 3 x 3 = 9 Output 9 OK - Maximum product achieved! Key Insight: With n up to 12, we can enumerate all 2^n subsequences using bitmasks. For each pair of masks where (mask1 AND mask2) = 0 (ensuring disjoint), we check if both form palindromes and track the maximum product. Time complexity: O(3^n) where n is string length, using subset enumeration optimization. TutorialsPoint - Maximum Product of the Length of Two Palindromic Subsequences | Optimal Solution
Asked in
Google 15 Amazon 12 Microsoft 8
35.7K Views
Medium Frequency
~25 min Avg. Time
892 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