Palindromic patitioning | Practice | GeeksforGeeks

Given a string str, a partitioning of the string is a palindrome partitioning if every sub-string of the partition is a palindrome. Determine the fewest cuts needed for palindrome partitioning of given string.

Example 1:
Input: str = "ababbbabbababa"
Output: 3
Explaination: After 3 partitioning substrings 
are "a", "babbbab", "b", "ababa".

Example 2:
Input: str = "aaabba"
Output: 1
Explaination: The substrings after 1
partitioning are "aa" and "abba".

Your Task:
You do not need to read input or print anything, Your task is to complete the function palindromicPartition() which takes the string str as input parameter and returns minimum number of partitions required.

Expected Time Complexity: O(n*n) [n is the length of the string str]
Expected Auxiliary Space: O(n*n)

Constraints:
1 ≤ length of str ≤ 500
0
mnagalkar3711 week ago
Java Solution using DP
execution time: 0.36 sec
 
class Solution{
    static int palindromicPartition(String str){
        int n = str.length();
        int[][] dp = new int[n][n];
        for(int g = 0; g < n; g++){
            for(int i = 0, j = g; i < n && j < n; i++, j++){
                if(i == j){
                    dp[i][j] = 0;
                }
                else if(g == 1){
                    dp[i][j] = (str.charAt(i) == str.charAt(j))? 0:1;
                }
                else{
                    if(str.charAt(i) == str.charAt(j) && dp[i+1][j-1] == 0)
                        dp[i][j] = 0;
                    else{
                        int min = Integer.MAX_VALUE;
                        for(int tempi = i+1, tempj = j-g; tempi < n && tempj < j; tempi++, tempj++){
                            int num1 = dp[i][tempj];
                            int num2 = dp[tempi][j];
                            min = Math.min(min, num1+num2);
                        }
                        dp[i][j] = min+1;
                    }
                }
            }
        }
        
        return dp[0][n-1];
    }
}
0
milindprajapatmst191 week ago
Time: 0.01/4.6
Time Complexity: O(n*n)
Space Complexity: O(n*n)
Idea: palindromic substring + dfs
 
class Solution {
public:
    int dp[500];
    vector<int> edges[500];
    int help(int u, string& str) {
        if (u == str.size())
            return 0;
        if (dp[u] == -1) {
            int result = help(u + 1, str);
            for (int& v : edges[u])
                result = min(result, help(v + 1, str));
            dp[u] = result + 1;
        }
        return dp[u];
    }
    int palindromicPartition(string& str) {
        int n = str.size();
        for (int k = 0; k < n; k++) {
            int i = k - 1, j = k + 1;
            while (i >= 0 && j < n && str[i] == str[j]) { 
                edges[i].push_back(j);
                i--; j++; 
            };
            i = k, j = k + 1;
            while (i >= 0 && j < n && str[i] == str[j]) { 
                edges[i].push_back(j);
                i--; j++; 
            };
        }
        memset(dp, -1, sizeof(dp));
        return help(0, str) - 1;
    }
};
+2
shourya17agarwal2 weeks ago
GFG's PYTHON COMPILER is WORST.The solution wont be accepted even after optimising the memoized code. The same code in C++ is accepted. While the same code in python is a TLE. with 16/29 passed.
+4
rounakdiptaghosh19993 weeks ago
 int dp[1001][1001];    bool isPalindrome(string s,int i,int j)  {      while(i<j){          if(s[i]!=s[j]) return false;          i++;j--;      }      return true;  }    int solve(string s ,int i,int j)  {    if(i>=j) return dp[i][j]=0;    if(isPalindrome(s,i,j)==true) return dp[i][j]=0;    if(dp[i][j]!=-1)    return dp[i][j];    int mn=INT_MAX;    for(int k=i;k<=j-1;k++){       //  int temp=solve(s,i,k)+solve(s,k+1,j)+1;       int right,left;        if(dp[i][k]!=-1){         left = dp[i][k];        }        else {        left = solve(s,i,k);        }        dp[i][k]=left;        if(dp[k+1][j]!=-1)          right =dp[k+1][j];        else right=solve(s,k+1,j);        dp[k+1][j]=right;        int temp = 1+left+right;        mn=min(temp,mn);    }    return dp[i][j]=mn;  }
   int palindromicPartition(string str)   {       // code here       memset(dp,-1,sizeof(dp));       int n = str.length();       return solve(str,0,n-1);   }
+1
shivam1706203 weeks ago
int dp[501][501];bool ispalin(string &str , int l , int r){   while(l<r)   {       if(str[l]!=str[r])       {           return false;       }       l++;       r--;   }      return true;}   int func(int l , int r , string &str )   {       if(l>=r)       {           return dp[l][r]= 0;       }              if(ispalin(str , l ,r))       {           return 0;       }              if(dp[l][r]!=-1)       {           return dp[l][r];       }              int res=INT_MAX;                     for(int k=l;k<r;k++)       {           res=min(res , 1 + func(l , k , str) + func(k+1 , r , str));       }              return dp[l][r]=res;   }   int palindromicPartition(string str)   {       // code here       memset(dp , -1 , sizeof(dp));       int n=str.size();       return func(0 , n-1 , str);   }
+1
awasthi007here1 month ago
    int dp[501][501];    bool ispalindrome(string &s, int i , int j){      while(i<=j){          if(s[i]==s[j]){              i++;              j--;          }          else{              return false;          }      }      return true;  }        int helper(string str, int i, int j)    {        if(i >= j)            return dp[i][j] = 0;                if(ispalindrome(str, i, j))            return dp[i][j] = 0;                    if(dp[i][j] != -1)            return dp[i][j];                                    int ans = INT_MAX;  // max length                for(int k=i; k<=j-1; k++)        {          int temp=helper(str, i, k)+helper(str, k+1, j) + 1;            ans = min(temp, ans);        }        return dp[i][j] = ans;    }            int palindromicPartition(string str)    {        // code here        memset(dp, -1, sizeof(dp));        //int n = ;        return helper(str, 0, str.size()-1);    }
 
 
above code shows TLE please help
 
0
detroix07
This comment was deleted.
0
kambojabhishek0611 month ago
// java solution using dp
class Solution{   static int palindromicPartition(String str)   {       // code here       boolean[][]dp=new boolean[str.length()][str.length()];       for(int g=0;g<str.length();g++){           for(int i=0,j=g;j<str.length();i++,j++){               if(g==0){                 dp[i][j]=true;                 }                else if(g==1){                   if(str.charAt(i)==str.charAt(j)){                       dp[i][j]=true;                   }                   else {                       dp[i][j]=false;                   }               }               else{                   if(str.charAt(i)==str.charAt(j)&&dp[i+1][j-1]==true){                       dp[i][j]=true;                   }                   else {                       dp[i][j]=false;                   }               }           }       }              int strj[]=new int[str.length()];       strj[0]=0;       for(int j=1;j<strj.length;j++){                      int min = Integer.MAX_VALUE;           if(dp[0][j]) {               strj[j]=0;           }           else{           for(int i=j;i>=1;i--){               if(dp[i][j]){                   if(strj[i-1]<min) {                       min=strj[i-1];                   }               }               }           strj[j]=min+1;       }       }       return strj[str.length()-1];   }}
0
akashmr10961 month ago
 static int palindromicPartition(String str)
    {
        int n = str.length();
        boolean[][] palinIndices = new boolean[n][n];
        
        for(int i=0; i<n; i++) {
            for(int j=i; j<n; j++) {
                palinIndices[i][j] = isPalin(str, i, j);
                //System.out.println(String.format("i: %d j: %d value: %s", i, j, palinIndices[i][j]));
            }
        }
        
        int dp[] = new int[n];
        
        for(int i=0; i<n; i++) {
            if(palinIndices[0][i]) {
                dp[i] = 0;
            } else {
                dp[i] = i;
                for(int j=i; j>=0; j--) {
                    if (palinIndices[j][i]) {
                        dp[i] = Math.min(dp[i], j == 0 ? 0 : dp[j-1]);
                    }
                }
                dp[i]++;
            }
            //System.out.println("i: " + i + " dp: " + dp[i]);
        }
        
        return dp[n-1];
    }
    
    static boolean isPalin(String s, int start, int end) {
        for(int i=start, j=end; i<j; i++, j--) {
            if (s.charAt(i) != s.charAt(j)) {
                return false;
            }
        }
        return true;
    }
0
hamidnourashraf1 month ago
Time: 0.3/13.0

import math
class Solution:
    def is_palindrom(self, string):  ## bottom_up approach
        i = 0
        j = len(string) -1
        while i < j:
            if string[i] != string[j]:
                return False
            i += 1
            j -= 1
        return True
    
    def palindromicPartition(self, string):
        n = len(string)
        n_cuts = [0] * n
        for i in range(1, n):
            if self.is_palindrom(string[0:i+1]):
                n_cuts[i] = 0
            else:
                _min = math.inf
                for k in range(1, i+1):
                    if self.is_palindrom(string[k:i+1]):
                        _min = min(_min, 1 + n_cuts[k-1])
                n_cuts[i] = _min
        return n_cuts[-1]
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.