Count Palindromic Subsequences | Practice | GeeksforGeeks

Given a string str of length N, you have to find number of palindromic subsequence (need not necessarily be distinct) which could be formed from the string str.
Note: You have to return the answer module 109+7;
 
Example 1:
Input: 
Str = "abcd"
Output: 
4
Explanation:
palindromic subsequence are : "a" ,"b", "c" ,"d"
 
Example 2:
Input: 
Str = "aab"
Output: 
4
Explanation:
palindromic subsequence are :"a", "a", "b", "aa"
 
Your Task:
You don't need to read input or print anything. Your task is to complete the function countPs() which takes a string str as input parameter and returns the number of palindromic subsequence.
 
Expected Time Complexity: O(N*N)
Expected Auxiliary Space: O(N*N)

Constraints:
1<=length of string str <=1000
0
abhishekwasu20014 days ago
this code is running for 102 test cases but not for rest of three 
can anyone tell me what is going wrong and how can get rid of this  plz plz
 
 
 
long long int  countPS(string str)   {         long long int dp[str.length()+1][str.length()+1];              for(int i=0;i<str.length();i++)       for(int j=0;j<str.length();j++)         dp[i][j]=0;               for(int i=0;i<str.length();i++)       dp[i][i]=1;         long long int j=1,k=0,i=0;      while(j<str.length())      {          k=j;          i=0;          while(k<str.length())          {           // cout<<"value of i is "<<i<<" value of j is "<<k<<endl;              if(str[i]==str[k])                dp[i][k]=1+dp[i+1][k]+dp[i][k-1];                             else                dp[i][k]=dp[i+1][k]+dp[i][k-1]-dp[i+1][k-1];                              i++;              k++;          }          j++;      }      return dp[0][str.length()-1];   }
+1
milindprajapatmst196 days ago
# define ll long long
const int N = 1e3, MOD = 1e9 + 7;
ll dp[N][N];
ll _add(ll x, ll y) {
    return (x + y) % MOD;
}
ll _sub(ll x, ll y) {
    return (x - y) + (x >= y ? 0 : MOD);
}
ll _mul(ll x, ll y) {
    return (x * y) % MOD;
}
class Solution {
    public:
    ll help(int k1, int k2, string& str) {
        if (k1 > k2)
            return 0;
        if (k1 == k2)
            return 1;
        if (dp[k1][k2] == -1) {
            ll result = _sub(_add(help(k1 + 1, k2, str), help(k1, k2 - 1, str)), help(k1 + 1, k2 - 1, str));
            if (str[k1] == str[k2])
                result = _add(result, _add(1, help(k1 + 1, k2 - 1, str)));
            dp[k1][k2] = result;
        }
        return dp[k1][k2];
    }
    ll countPS(string& str) {
        memset(dp, -1, sizeof(dp));
        return help(0, str.size() - 1, str);
    }
     
};
-1
anuragshubham341 week ago
class Solution{  static long[][] dp=new long[1001][1001];  static long  m=1000000007;  static long solve (String str,int i,int j){      if(i>j)      return 0;      if(i==j)      return 1;       if(dp[i][j]!=-1)        return dp[i][j];             if(str.charAt((int)i)==str.charAt((int)j))       return dp[i][j]=(solve(str,i+1,j)+solve(str,i,j-1)+1)%m;       else        return dp[i][j]=(m+solve(str,i+1,j)%m+solve(str,i,j-1)%m-solve(str,i+1,j-1)%m)%m;          }  static long countPS(String str)   {     for(long[] a:dp)      Arrays.fill(a,-1);     return solve(str,0,str.length()-1);     }}
+1
sparshtanejaa1 week ago
all thos getting tle use this 
 
long long m = 1e9 + 7;   int dp[1001][1001];      long long int cps(string &s,int i,int j)   {       if(i > j) return 0;        if(i == j) return 1;        if(dp[i][j] != -1) return dp[i][j];        if(s[i] == s[j])       {         return  dp[i][j] = ( 1 + cps(s,i+1,j) + cps(s,i,j-1))%m;       }       else       {          return dp[i][j] = (m+ cps(s,i+1,j) + cps(s,i,j-1) - cps(s,i+1,j-1))%m;       }      // return dp[i][j]%m;   }      long long int  countPS(string s)   {      //Your code here     memset(dp,-1,sizeof(dp));     return cps(s,0,s.size() -1);   }    
0
shilsoumyadip2 weeks ago
int dp[1001][1001];     long long int m = 1e9 + 7;      long long int solve(string &s , int i , int j)   {       if(i>j) return 0;       if(i==j) return 1;              if(dp[i][j] != -1)        return dp[i][j];                     if(s[i] == s[j])       {           return dp[i][j] = (solve(s,i+1,j) + solve(s,i,j-1) + 1)%m;       }       else       {           return dp[i][j] = (m + solve(s,i+1,j) + solve(s,i,j-1) - solve(s,i+1,j-1))%m;       }   }               long long int  countPS(string str)   {      //Your code here   //int dp[str.length()][str.length()];      memset(dp,-1,sizeof(dp));      return solve(str,0,str.size()-1);      
0
ishrivastava253 weeks ago
To avoid TLE, just pass the string by reference and take a mod when returning dp , see soln below , P.S :: We are adding mod to avoid negative solution, as we are subtarcting the recursive func also. 
 
int dp[1001][1001];    long long int m = 1e9 + 7;   long long int helper(string &str,int i,int j)   {       if(i>j) return 0;       if(i==j) return 1;       if(dp[i][j]!=-1) return (dp[i][j]);       if(str[i]==str[j]) return dp[i][j]= (1+ helper(str,i+1,j) + helper(str,i,j-1))%m;       else return dp[i][j]= ( m + helper(str,i+1,j) + helper(str,i,j-1) - helper(str,i+1,j-1))%m;   }      long long int  countPS(string str)   {      memset(dp,-1,sizeof(dp));      int n=str.size();      return helper(str,0,n-1);   }
 
+1
sandeepbhutia20111 month ago
Can anyone please explain why my code giving negative value even if i have used mod
 
    /*You are required to complete below method */   long long int val=1000000007;      long long int  countPS(string str)   {      //Your code here    int N=str.size();
   vector<vector<long long int>> cnt(N+1,vector<long long int>(N+1,0));    for(int i=0;i<=N;i++){      cnt[i][i]=1;   }   for(int i=1;i<=N;i++){      for(int j=0;j<=N-i;j++){          if(str[j]==str[j+i]){              cnt[j][j+i]=(cnt[j][j+i-1] % val+cnt[j+1][j+i] % val+1)% val;          }          else{              cnt[j][j+i]=(cnt[j][j+i-1] % val +                            cnt[j+1][j+i] % val -cnt[j+1][j+i-1] % val )% val;          }      }  }  return cnt[0][N-1] % val;}
 
+2
deskhell2 months ago
To come up with a intuition for this problem is pretty tough I suggest.
class Solution{
    public:
    /*You are required to complete below method */
    long long int  countPS(string s)
    {
        int n = s.size();
        const int mod = 1e9+7;
        
        long long dp[n][n];
        for(int g = 0; g < n; g++){
            for(int i = 0, j = g; j < n; i++, j++){
                if(g == 0)dp[i][j] = 1;
                else if(g == 1)dp[i][j] = s[i] == s[j] ? 3 : 2;
                else{
                    if(s[i] == s[j])
                        dp[i][j] = (dp[i][j-1] % mod + dp[i+1][j] % mod + 1) % mod;
                    else 
                        dp[i][j] = (dp[i][j-1] % mod + dp[i+1][j] % mod - dp[i+1][j-1] + mod) % mod;
                }
            }
        }
        return dp[0][n-1];
    }
     
};
-1
itsmanan132 months ago
Can someone please help my code is giving TLE I don't know why...
 
class Solution{
public:
    /*You are required to complete below method */
    long long int m = 1e9 + 7;
    long long int dp[1005][1005];
    long long int helper(int i,int j,string str)
    {
        if(i>j)
            return 0;
        if(i==j)
            return 1;
        if(dp[i][j]!=-1) 
            return dp[i][j];
        if(str[i]==str[j])
            return dp[i][j] = (1%m + helper(i+1,j,str)%m + helper(i,j-1,str)%m)%m;
        else
            return dp[i][j] = (helper(i+1,j,str)%m + helper(i,j-1,str)%m - 
                                                            helper(i+1,j-1,str)%m)%m;
    }
    long long int  countPS(string str)
    {
       //Your code here
       memset(dp,-1,sizeof(dp));
       int n = str.length();
       return helper(0,n-1,str)%m;
    }
     
};
+2
ruchitchudasama1232 months ago
simple and easy to understand code, if you hve any query regarding this approach or not able to understand code let me know.
https://auth.geeksforgeeks.org/user/ruchitchudasama123/practice/
public:
    /*You are required to complete below method */
    long long int M=1e9+7;
    
    long long int go(int i,int j,string &str,vector<vector<long long int>> &dp){
        if(i>j)return 0;
        
        if(i==j)return 1;
        
        if(dp[i][j]!=-1)return dp[i][j];
        
        long long int ans=0;
        
        if(str[i]==str[j]){
            ans=1+go(i+1,j,str,dp)+go(i,j-1,str,dp)%M;
        }
        else{
            ans=go(i+1,j,str,dp)+go(i,j-1,str,dp)-go(i+1,j-1,str,dp);
        }
        return dp[i][j]=ans;
    }
    
    long long int countPS(string str)
    {
        int n=str.size();
        vector<vector<long long int>> dp(n+1,vector<long long int>(n+1,-1));
        return go(0,n-1,str,dp)%M;
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.