Count Different Palindromic Subsequences - Problem
Given a string s, you need to find the number of different non-empty palindromic subsequences that can be formed from it. This is a challenging problem that combines string manipulation with dynamic programming!
๐ฏ What you need to do:
- Count all possible palindromic subsequences (not substrings!)
- A subsequence is formed by deleting zero or more characters while maintaining order
- A sequence is palindromic if it reads the same forwards and backwards
- Two subsequences are different if they differ at any position
โ ๏ธ Important: Since the answer can be very large, return it modulo 10^9 + 7.
Example: For string "bccb", the palindromic subsequences are: "b", "c", "cc", "bcb", "bccb" โ Answer: 6
Input & Output
example_1.py โ Basic Case
$
Input:
s = "bccb"
โบ
Output:
6
๐ก Note:
The palindromic subsequences are: "b" (appears twice but we count unique strings), "c" (appears twice but counts as one), "cc", "bcb", "bccb". Total unique palindromic subsequences: 6
example_2.py โ All Same Character
$
Input:
s = "abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba"
โบ
Output:
104860361
๐ก Note:
With repeating patterns, we get many different palindromic subsequences. The DP approach efficiently handles the exponential growth.
example_3.py โ Single Character
$
Input:
s = "a"
โบ
Output:
1
๐ก Note:
Only one palindromic subsequence possible: "a"
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Base Cases
Every single character is a palindrome by itself
2
Build Up Ranges
For each substring, decide based on whether endpoints match
3
Handle Matches
When endpoints match, we can form new palindromes by wrapping them around inner palindromes
4
Handle Non-matches
When endpoints don't match, combine counts from two overlapping subproblems
5
Apply Modular Arithmetic
Keep results within bounds using modulo 10^9 + 7
Key Takeaway
๐ฏ Key Insight: By recognizing that palindromes have symmetric structure, we can use dynamic programming to count them efficiently in O(nยฒ) time instead of the brute force O(2^n) approach.
Time & Space Complexity
Time Complexity
O(nยฒ)
We solve O(nยฒ) subproblems, each taking O(n) time in worst case
โ Quadratic Growth
Space Complexity
O(nยฒ)
2D DP table to store results for all substrings
โ Quadratic Space
Constraints
- 1 โค s.length โค 1000
- s consists only of lowercase English letters
- Return the answer modulo 109 + 7
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code