Tutorialspoint
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.
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.
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)
Dynamic Programming CapgeminiLTIMindtree
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Create a 3D DP table dp[i][j][c] where i and j are indices and c represents characters 'a', 'b', 'c', 'd'
 Step 2: Initialize base cases - single characters form palindromes of count 1
 Step 3: For each substring length from 2 to n, fill the DP table
 Step 4: For each character c, if s[i] == s[j] == c, then palindromes = 2 + sum of all inner palindromes
 Step 5: If only one end matches character c, copy count from the substring excluding the non-matching end
 Step 6: If neither end matches c, copy count from the inner substring
 Step 7: Sum up all dp[0][n-1][c] for all characters c and return the result modulo 10^9 + 7

Submitted Code :