
Problem
Solution
Submissions
Different Palindromic Subsequences
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C program to count the number of different non-empty palindromic subsequences in a given string. Since the answer may be very large, return it modulo 10^9 + 7. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Example 1
- Input: s = "bccb"
- Output: 6
- Explanation:
- The 6 different palindromic subsequences are 'b', 'c', 'c', 'b', 'cc', 'bccb'.
- Note that 'bcb' is not a valid subsequence since the characters must maintain their original order.
- Therefore, the total count is 6.
- The 6 different palindromic subsequences are 'b', 'c', 'c', 'b', 'cc', 'bccb'.
Example 2
- Input: s = "abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba"
- Output: 104860361
- Explanation:
- This is a complex string with many possible palindromic subsequences.
- We need to count all different palindromic subsequences efficiently.
- The result is 104860361 after taking modulo 10^9 + 7.
- This is a complex string with many possible palindromic subsequences.
Constraints
- 1 <= s.length <= 1000
- s[i] is either 'a', 'b', 'c', or 'd'
- The answer should be returned modulo 10^9 + 7
- Time Complexity: O(n^3)
- Space Complexity: O(n^2)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use dynamic programming with 3D table dp[i][j][c] representing count of palindromes from index i to j starting and ending with character c
- For each character 'a', 'b', 'c', 'd', calculate palindromes separately
- Base case: single characters form palindromes of length 1
- For longer substrings, if s[i] == s[j] == c, then dp[i][j][c] = 2 + sum of all dp[i+1][j-1][x] for all characters x
- If characters don't match at ends, copy from smaller ranges
- Use modular arithmetic to avoid overflow