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 INPUT String s = "bccb" b idx 0 c idx 1 c idx 2 b idx 3 All Palindromes: "b" "c" "bb" "cc" "bcb" "bccb" Length: 4 Unique chars: b, c ALGORITHM STEPS 1 Initialize DP Table dp[i][j] = count for s[i..j] 2 Base Case Single char: dp[i][i] = 1 3 Expand Substrings Process by length 2 to n 4 Recurrence Count by boundary chars DP Table dp[i][j]: j 0 1 2 3 i=0 1 2 4 6 i=1 - 1 3 4 i=2 - - 1 2 i=3 - - - 1 FINAL RESULT dp[0][n-1] = dp[0][3] 6 OK - Answer Found! 6 Unique Palindromes: "b" "c" "bb" "cc" "bcb" "bccb" Return: 6 mod (10^9+7) = 6 Time: O(n^2), Space: O(n^2) Key Insight: The DP recurrence depends on boundary characters. If s[i] == s[j], we can form new palindromes by wrapping inner palindromes. We must track first/last occurrence of each character to avoid counting duplicates. Formula: dp[i][j] = 2*dp[i+1][j-1] + 2 (when boundaries match with no inner dup) TutorialsPoint - Count Different Palindromic Subsequences | Dynamic Programming
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