Count Different Palindromic Subsequences - Problem

Given a string s, return the number of different non-empty palindromic subsequences in s. Since the answer may be very large, return it modulo 10⁹ + 7.

A subsequence of a string is obtained by deleting zero or more characters from the string. A sequence is palindromic if it is equal to the sequence reversed.

Two sequences a₁, a₂, ... and b₁, b₂, ... are different if there is some i for which aᵢ ≠ bᵢ.

Input & Output

Example 1 — Basic Case
$ Input: s = "bccb"
Output: 6
💡 Note: The different palindromic subsequences are: "b", "c", "cc", "b" (from end), "bcb", "bccb". Total count is 6.
Example 2 — Single Character
$ Input: s = "abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba"
Output: 104860361
💡 Note: Long string with many different characters creates exponentially many palindromic subsequences, result is modulo 10^9 + 7.
Example 3 — Repeated Characters
$ Input: s = "aaa"
Output: 3
💡 Note: The palindromic subsequences are: "a" (appears 3 times but counted once), "aa" (appears 3 times but counted once), "aaa" (appears once). Total unique count is 3.

Constraints

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

Visualization

Tap to expand
Count Different Palindromic Subsequences: "bccb"bccbPalindromic Subsequences Found:Unique Palindromes:"b" (single char) • "c" (single char) • "cc" (adjacent)"bcb" (positions 0,1,3) • "bccb" (full string)Total: 6 different palindromic subsequencesOutput: 6Result returned modulo 10⁹ + 7
Understanding the Visualization
1
Input String
Given string with characters to analyze
2
Find Palindromes
Identify all unique palindromic subsequences
3
Count Result
Return count modulo 10^9 + 7
Key Takeaway
🎯 Key Insight: Use interval DP to systematically count palindromes while avoiding duplicates through careful boundary analysis
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
62.0K Views
Medium Frequency
~35 min Avg. Time
1.8K 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