The Wayback Machine - https://web.archive.org/web/20240930221929/https://www.geeksforgeeks.org/palindrome-partitioning-dp-17/
Open In App

Palindrome Partitioning

Last Updated : 08 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Hard
27.82%
1.4L

Given a string str, a partitioning of the string is a palindrome partitioning if every sub-string of the partition is a palindrome, the task is to find the minimum number of cuts needed for palindrome partitioning of the given string.

Palindrome Partition

Examples :  

Input: str = “geek” 
Output: 2 
Explanation: We need to make minimum 2 cuts, i.e., “g ee k”

Input: str = “aaaa” 
Output: 0 
Explanation: The string is already a palindrome.

Input: str = “abcde” 
Output: 4

Input: str = “abbac” 
Output: 1 

Recommended Practice

Recursive Approach for Palindrome Partitioning:

This is the naive approach to solving the Palindrome Partitioning problem. In this approach, we will try to apply all possible partitions and at the end return the correct combination of partitions.

This approach is similar to that of Matrix Chain Multiplication problem.

In this approach, we recursively evaluate the following conditions:

  • If the current string is a palindrome, then we simply return true, as Palindrome Partitioning is possible.
  • Else, like the Matrix Chain Multiplication problem,
    • we try making cuts at all possible places,
    • recursively calculate the cost for each cut
    • return the minimum value.

Below is the implementation of the above approach.

C++




// C++ Code for Palindrome Partitioning
// Problem
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to Check if a substring is a palindrome
bool isPalindrome(string String, int i, int j)
{
    while (i < j) {
        if (String[i] != String[j])
            return false;
        i++;
        j--;
    }
    return true;
}
 
// Function to find the minimum number of cuts needed for
// palindrome partitioning
int minPalPartion(string String, int i, int j)
{
    // Base case: If the substring is empty or a palindrome,
    // no cuts needed
    if (i >= j || isPalindrome(String, i, j))
        return 0;
 
    int ans = INT_MAX, count;
 
    // Iterate through all possible partitions and find the
    // minimum cuts needed
    for (int k = i; k < j; k++) {
        count = minPalPartion(String, i, k)
                + minPalPartion(String, k + 1, j) + 1;
        ans = min(ans, count);
    }
 
    return ans;
}
 
// Driver code
int main()
{
    string str = "ababbbabbababa";
 
    // Find the minimum cuts needed for palindrome
    // partitioning and display the result
    cout
        << "Min cuts needed for Palindrome Partitioning is "
        << minPalPartion(str, 0, str.length() - 1) << endl;
 
    return 0;
}


Java




//
public class PalindromePartitioning {
 
    // Function to Check if a substring is a palindrome
    static boolean isPalindrome(String str, int i, int j)
    {
        while (i < j) {
            if (str.charAt(i) != str.charAt(j))
                return false;
            i++;
            j--;
        }
        return true;
    }
 
    // Function to find the minimum number of cuts needed
    // for palindrome partitioning
    static int minPalPartition(String str, int i, int j)
    {
        // Base case: If the substring is empty or a
        // palindrome, no cuts needed
        if (i >= j || isPalindrome(str, i, j))
            return 0;
 
        int minCuts = Integer.MAX_VALUE;
 
        // Iterate through all possible partitions and find
        // the minimum cuts needed
        for (int k = i; k < j; k++) {
            int cuts = minPalPartition(str, i, k)
                       + minPalPartition(str, k + 1, j) + 1;
            minCuts = Math.min(minCuts, cuts);
        }
 
        return minCuts;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String str = "ababbbabbababa";
 
        // Find the minimum cuts needed for palindrome
        // partitioning and display the result
        System.out.println(
            "Min cuts needed for Palindrome Partitioning is "
            + minPalPartition(str, 0, str.length() - 1));
    }
}


C#




using System;
 
// Function to Check if a substring is a palindrome
public class PalindromePartitioning {
 
    // Function to Check if a substring is a palindrome
    static bool IsPalindrome(string str, int i, int j)
    {
        while (i < j) {
            if (str[i] != str[j])
                return false;
            i++;
            j--;
        }
        return true;
    }
 
    // Function to find the minimum number of cuts needed
    // for palindrome partitioning
    static int MinPalPartition(string str, int i, int j)
    {
        // Base case: If the substring is empty or a
        // palindrome, no cuts needed
        if (i >= j || IsPalindrome(str, i, j))
            return 0;
 
        int minCuts = int.MaxValue;
 
        // Iterate through all possible partitions and find
        // the minimum cuts needed
        for (int k = i; k < j; k++) {
            int cuts = MinPalPartition(str, i, k)
                       + MinPalPartition(str, k + 1, j) + 1;
            minCuts = Math.Min(minCuts, cuts);
        }
 
        return minCuts;
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        string str = "ababbbabbababa";
 
        // Find the minimum cuts needed for palindrome
        // partitioning and display the result
        Console.WriteLine(
            "Min cuts needed for Palindrome Partitioning is "
            + MinPalPartition(str, 0, str.Length - 1));
    }
}


Javascript




<script>
 
// Javascript code for Palindrome
// Partitioning Problem
 
// Function to Check if a substring is a palindrome
function isPalindrome(String, i, j)
{
    while (i < j)
    {
        if (String[i] != String[j])
            return false;
             
        i++;
        j--;
    }
    return true;
}
 
// Function to find the minimum number of cuts needed
// for palindrome partitioning
function minPalPartion(String, i, j)
{
    // Base case: If the substring is empty or a palindrome,
    // no cuts needed
    if (i >= j || isPalindrome(String, i, j))
        return 0;
         
    let ans = Number.MAX_VALUE, count;
     
     
    // Iterate through all possible partitions and find the
    // minimum cuts needed
    for(let k = i; k < j; k++)
    {
        count = minPalPartion(String, i, k) +
        minPalPartion(String, k + 1, j) + 1;
        ans = Math.min(ans, count);
    }
    return ans;
}
 
// Driver code
let str = "ababbbabbababa";
 
// Find the minimum cuts needed for palindrome
// partitioning and display the result
document.write("Min cuts needed for " +
               "Palindrome Partitioning is " +
               minPalPartion(str, 0, str.length - 1));
 
</script>


Python3




# Function to Check if a substring is a palindrome
def is_palindrome(string, i, j):
 
    while i < j:
        if string[i] != string[j]:
            return False
        i += 1
        j -= 1
    return True
 
#  Function to find the minimum number of cuts needed for palindrome partitioning
 
 
def min_pal_partition(string, i, j):
 
    # Base case: If the substring is empty or a palindrome, no cuts needed
    if i >= j or is_palindrome(string, i, j):
        return 0
 
    ans = float('inf')
 
    # Iterate through all possible partitions and find the minimum cuts needed
    for k in range(i, j):
        count = min_pal_partition(string, i, k) + \
            min_pal_partition(string, k + 1, j) + 1
        ans = min(ans, count)
 
    return ans
 
 
# Driver code
if __name__ == "__main__":
    str = "ababbbabbababa"
 
    # Find the minimum cuts needed for palindrome partitioning and display the result
    print("Min cuts needed for Palindrome Partitioning is",
          min_pal_partition(str, 0, len(str) - 1))


Output

Min cuts needed for Palindrome Partitioning is 3

Time Complexity: O(2n)
Auxiliary Space: O(n)

Optimising Overlapping Sub-problems in Recursive Approach for Palindrome Partitioning in (O(n3)):

The above recursive approach has overlapping subproblems, leading to redundant computations thereby resulting in exponential time complexity. This redundant computation can be solved by using Dynamic programming approach.

Here, we can use two 2D array C[][] and P[][], for storing the computed result.

  • C[i][j] stores the minimum number of cuts needed for the substring str[i..j],
  • while P[i][j] stores whether the substring str[i..j] is a palindrome or not.
  • It starts with smaller substrings and gradually builds up to the entire string.

Below is the implementation of the above approach:

C++




// Dynamic Programming Solution for
// Palindrome Partitioning Problem
#include <bits/stdc++.h>
using namespace std;
 
// Returns the minimum number of cuts
// needed to partition a string
// such that every part is a palindrome
int minPalPartion(string str)
{
    // Get the length of the string
    int n = str.length();
 
    // Create two arrays to build the solution in bottom up
    // manner
 
    // C[i][j] = Minimum number of cuts needed for
    // palindrome partitioning of substring str[i..j]
    int C[n][n];
 
    // P[i][j] = true if substring str[i..j] is palindrome,
    // else false
    bool P[n][n];
 
    // Note that C[i][j] is 0 if P[i][j] is true
 
    // Every substring of length 1 is a palindrome
    for (int i = 0; i < n; i++) {
        P[i][i] = true;
        C[i][i] = 0;
    }
 
    // L is substring length. Build the
    // solution in bottom up manner by
    // considering all substrings of
    // length starting from 2 to n.
    // The loop structure is same as Matrix
    // Chain Multiplication problem
    for (int L = 2; L <= n; L++) {
 
        // For substring of length L, set
        // different possible starting indexes
        for (int i = 0; i < n - L + 1; i++) {
            int j = i + L - 1; // Set ending index
 
            // If L is 2, then we just need to
            // compare two characters. Else
            // need to check two corner characters
            // and value of P[i+1][j-1]
            if (L == 2)
                P[i][j] = (str[i] == str[j]);
            else
                P[i][j]
                    = (str[i] == str[j]) && P[i + 1][j - 1];
 
            // IF str[i..j] is palindrome, then C[i][j] is 0
            if (P[i][j] == true)
                C[i][j] = 0;
            else {
 
                // Make a cut at every possible
                // location starting from i to j,
                // and get the minimum cost cut.
                C[i][j] = INT_MAX;
                for (int k = i; k <= j - 1; k++)
                    C[i][j] = min(
                        C[i][j], C[i][k] + C[k + 1][j] + 1);
            }
        }
    }
 
    // Return the min cut value for
    // complete string. i.e., str[0..n-1]
    return C[0][n - 1];
}
 
// Driver code
int main()
{
    string str = "ababbbabbababa";
    cout << "Min cuts needed for Palindrome"
            " Partitioning is "
         << minPalPartion(str);
    return 0;
}
 
// This code is contributed by rathbhupendra


C




// Dynamic Programming Solution for Palindrome Partitioning
// Problem
#include <limits.h>
#include <stdio.h>
#include <string.h>
 
// A utility function to get minimum of two integers
int min(int a, int b) { return (a < b) ? a : b; }
 
// Returns the minimum number of cuts needed to partition a
// string such that every part is a palindrome
int minPalPartion(char* str)
{
    // Get the length of the string
    int n = strlen(str);
 
    /* Create two arrays to build the solution in bottom up
       manner C[i][j] = Minimum number of cuts needed for
       palindrome partitioning of substring str[i..j]
       P[i][j] = true if substring str[i..j] is palindrome,
       else false
       Note that C[i][j] is 0 if P[i][j] is true */
    int C[n][n];
    bool P[n][n];
 
    int i, j, k, L; // different looping variables
 
    // Every substring of length 1 is a palindrome
    for (i = 0; i < n; i++) {
        P[i][i] = true;
        C[i][i] = 0;
    }
 
    /* L is substring length. Build the solution in bottom
       up manner by considering all substrings of length
       starting from 2 to n. The loop structure is same as
       Matrix Chain Multiplication problem.
   */
    for (L = 2; L <= n; L++) {
        // For substring of length L, set different possible
        // starting indexes
        for (i = 0; i < n - L + 1; i++) {
            j = i + L - 1; // Set ending index
 
            // If L is 2, then we just need to compare two
            // characters. Else need to check two corner
            // characters and value of P[i+1][j-1]
            if (L == 2)
                P[i][j] = (str[i] == str[j]);
            else
                P[i][j]
                    = (str[i] == str[j]) && P[i + 1][j - 1];
 
            // IF str[i..j] is palindrome, then C[i][j] is 0
            if (P[i][j] == true)
                C[i][j] = 0;
            else {
 
                // Make a cut at every possible location
                // starting from i to j, and get the minimum
                // cost cut.
                C[i][j] = INT_MAX;
                for (k = i; k <= j - 1; k++)
                    C[i][j] = min(
                        C[i][j], C[i][k] + C[k + 1][j] + 1);
            }
        }
    }
 
    // Return the min cut value for complete string. i.e.,
    // str[0..n-1]
    return C[0][n - 1];
}
 
// Driver program to test above function
int main()
{
    char str[] = "ababbbabbababa";
    printf(
        "Min cuts needed for Palindrome Partitioning is %d",
        minPalPartion(str));
    return 0;
}


Java




// Java Code for Palindrome Partitioning
// Problem
public class GFG {
    // Returns the minimum number of cuts needed
    // to partition a string such that every
    // part is a palindrome
    static int minPalPartion(String str)
    {
        // Get the length of the string
        int n = str.length();
 
        /* Create two arrays to build the solution
           in bottom up manner
           C[i][j] = Minimum number of cuts needed
                     for palindrome partitioning
                     of substring str[i..j]
           P[i][j] = true if substring str[i..j] is
                     palindrome, else false
           Note that C[i][j] is 0 if P[i][j] is
           true */
        int[][] C = new int[n][n];
        boolean[][] P = new boolean[n][n];
 
        int i, j, k, L; // different looping variables
 
        // Every substring of length 1 is a palindrome
        for (i = 0; i < n; i++) {
            P[i][i] = true;
            C[i][i] = 0;
        }
 
        /* L is substring length. Build the solution in
         bottom up manner by considering all substrings
         of length starting from 2 to n. The loop
         structure is same as Matrix Chain Multiplication
        )*/
        for (L = 2; L <= n; L++) {
            // For substring of length L, set different
            // possible starting indexes
            for (i = 0; i < n - L + 1; i++) {
                j = i + L - 1; // Set ending index
 
                // If L is 2, then we just need to
                // compare two characters. Else need to
                // check two corner characters and value
                // of P[i+1][j-1]
                if (L == 2)
                    P[i][j]
                        = (str.charAt(i) == str.charAt(j));
                else
                    P[i][j]
                        = (str.charAt(i) == str.charAt(j))
                          && P[i + 1][j - 1];
 
                // IF str[i..j] is palindrome, then
                // C[i][j] is 0
                if (P[i][j] == true)
                    C[i][j] = 0;
                else {
                    // Make a cut at every possible
                    // localtion starting from i to j,
                    // and get the minimum cost cut.
                    C[i][j] = Integer.MAX_VALUE;
                    for (k = i; k <= j - 1; k++)
                        C[i][j] = Integer.min(
                            C[i][j],
                            C[i][k] + C[k + 1][j] + 1);
                }
            }
        }
 
        // Return the min cut value for complete
        // string. i.e., str[0..n-1]
        return C[0][n - 1];
    }
 
    // Driver program to test above function
    public static void main(String args[])
    {
        String str = "ababbbabbababa";
        System.out.println("Min cuts needed for "
                           + "Palindrome Partitioning is "
                           + minPalPartion(str));
    }
}
// This code is contributed by Sumit Ghosh


C#




// C# Code for Palindrome Partitioning
// Problem
using System;
 
class GFG {
    // Returns the minimum number of cuts needed
    // to partition a string such that every
    // part is a palindrome
    static int minPalPartion(String str)
    {
        // Get the length of the string
        int n = str.Length;
 
        /* Create two arrays to build the solution
        in bottom up manner
        C[i][j] = Minimum number of cuts needed
                    for palindrome partitioning
                    of substring str[i..j]
        P[i][j] = true if substring str[i..j] is
                    palindrome, else false
        Note that C[i][j] is 0 if P[i][j] is
        true */
        int[, ] C = new int[n, n];
        bool[, ] P = new bool[n, n];
 
        int i, j, k, L; // different looping variables
 
        // Every substring of length 1 is a palindrome
        for (i = 0; i < n; i++) {
            P[i, i] = true;
            C[i, i] = 0;
        }
 
        /* L is substring length. Build the solution in
        bottom up manner by considering all substrings
        of length starting from 2 to n. The loop
        structure is same as Matrix Chain Multiplication
        */
        for (L = 2; L <= n; L++) {
            // For substring of length L, set different
            // possible starting indexes
            for (i = 0; i < n - L + 1; i++) {
                j = i + L - 1; // Set ending index
 
                // If L is 2, then we just need to
                // compare two characters. Else need to
                // check two corner characters and value
                // of P[i+1][j-1]
                if (L == 2)
                    P[i, j] = (str[i] == str[j]);
                else
                    P[i, j] = (str[i] == str[j])
                              && P[i + 1, j - 1];
 
                // IF str[i..j] is palindrome, then
                // C[i][j] is 0
                if (P[i, j] == true)
                    C[i, j] = 0;
                else {
                    // Make a cut at every possible
                    // location starting from i to j,
                    // and get the minimum cost cut.
                    C[i, j] = int.MaxValue;
                    for (k = i; k <= j - 1; k++)
                        C[i, j] = Math.Min(
                            C[i, j],
                            C[i, k] + C[k + 1, j] + 1);
                }
            }
        }
 
        // Return the min cut value for complete
        // string. i.e., str[0..n-1]
        return C[0, n - 1];
    }
 
    // Driver program
    public static void Main()
    {
        String str = "ababbbabbababa";
        Console.Write("Min cuts needed for "
                      + "Palindrome Partitioning is "
                      + minPalPartion(str));
    }
}
 
// This code is contributed by Sam007


Javascript




<script>
// javascript Code for Palindrome Partitioning
// Problem
  
    // Returns the minimum number of cuts needed
    // to partition a string such that every
    // part is a palindrome
    function minPalPartion( str)
    {
     
        // Get the length of the string
        var n = str.length;
 
        /*
         * Create two arrays to build the solution in bottom up manner C[i][j] = Minimum
         * number of cuts needed for palindrome partitioning of substring str[i..j]
         * P[i][j] = true if substring str[i..j] is palindrome, else false Note that
         * C[i][j] is 0 if P[i][j] is true
         */
        var C = Array(n).fill().map(()=>Array(n).fill(0));
        var P =  Array(n).fill().map(()=>Array(n).fill(false));
 
        var i, j, k, L; // different looping variables
 
        // Every substring of length 1 is a palindrome
        for (i = 0; i < n; i++) {
            P[i][i] = true;
            C[i][i] = 0;
        }
 
        /*
         * L is substring length. Build the solution in bottom up manner by considering
         * all substrings of length starting from 2 to n. The loop structure is same as
         * Matrix Chain Multiplication problem
         */
        for (L = 2; L <= n; L++) {
            // For substring of length L, set different
            // possible starting indexes
            for (i = 0; i < n - L + 1; i++) {
                j = i + L - 1; // Set ending index
 
                // If L is 2, then we just need to
                // compare two characters. Else need to
                // check two corner characters and value
                // of P[i+1][j-1]
                if (L == 2)
                    P[i][j] = (str.charAt(i) == str.charAt(j));
                else
                    P[i][j] = (str.charAt(i) == str.charAt(j)) && P[i + 1][j - 1];
 
                // IF str[i..j] is palindrome, then
                // C[i][j] is 0
                if (P[i][j] == true)
                    C[i][j] = 0;
                else {
                    // Make a cut at every possible
                    // localtion starting from i to j,
                    // and get the minimum cost cut.
                    C[i][j] = Number.MAX_VALUE;
                    for (k = i; k <= j - 1; k++)
                        C[i][j] = Math.min(C[i][j], C[i][k] + C[k + 1][j] + 1);
                }
            }
        }
 
        // Return the min cut value for complete
        // string. i.e., str[0..n-1]
        return C[0][n - 1];
    }
 
    // Driver program to test above function
     
        var str = "ababbbabbababa";
        document.write("Min cuts needed for " + "Palindrome Partitioning is " + minPalPartion(str));
 
// This code is contributed by Rajput-Ji
</script>


PHP




<?php
// Dynamic Programming Solution for Palindrome Partitioning Problem
   
// Returns the minimum number of cuts needed to partition a string
// such that every part is a palindrome
function minPalPartion($str)
{
    // Get the length of the string
    $n = strlen($str);
   
    /* Create two arrays to build the solution in bottom up manner
       C[i][j] = Minimum number of cuts needed for palindrome partitioning
                 of substring str[i..j]
       P[i][j] = true if substring str[i..j] is palindrome, else false
       Note that C[i][j] is 0 if P[i][j] is true */
    $C = array_fill(0, $n, array_fill(0, $n, NULL));
    $P = array_fill(false, $n, array_fill(false, $n, NULL));
   
    // Every substring of length 1 is a palindrome
    for ($i=0; $i<$n; $i++)
    {
        $P[$i][$i] = true;
        $C[$i][$i] = 0;
    }
   
    /* L is substring length. Build the solution in a bottom-up manner by
       considering all substrings of length starting from 2 to n.
       The loop structure is same as Matrix Chain Multiplication problem
       */
    for ($L=2; $L<=$n; $L++)
    {
        // For substring of length L, set different possible starting indexes
        for ($i=0; $i<$n-$L+1; $i++)
        {
            $j = $i+$L-1; // Set ending index
   
            // If L is 2, then we just need to compare two characters. Else
            // need to check two corner characters and value of P[i+1][j-1]
            if ($L == 2)
                $P[$i][$j] = ($str[$i] == $str[$j]);
            else
                $P[$i][$j] = ($str[$i] == $str[$j]) && $P[$i+1][$j-1];
   
            // IF str[i..j] is palindrome, then C[i][j] is 0
            if ($P[$i][$j] == true)
                $C[$i][$j] = 0;
            else
            {
                // Make a cut at every possible location starting from i to j,
                // and get the minimum cost cut.
                $C[$i][$j] = PHP_INT_MAX;
                for ($k=$i; $k<=$j-1; $k++)
                    $C[$i][$j] = min ($C[$i][$j], $C[$i][$k] + $C[$k+1][$j]+1);
            }
        }
    }
   
    // Return the min cut value for complete string. i.e., str[0..n-1]
    return $C[0][$n-1];
}
   
// Driver program to test the above function
 
$str = "ababbbabbababa";
echo "Min cuts needed for Palindrome Partitioning is "
           .minPalPartion($str);
return 0;
?>


Python3




# Dynamic Programming Solution for
# Palindrome Partitioning Problem
 
# Returns the minimum number of
# cuts needed to partition a string
# such that every part is a palindrome
 
 
def minPalPartion(str):
 
    # Get the length of the string
    n = len(str)
 
    # Create two arrays to build the
    # solution in bottom up manner
    # C[i][j] = Minimum number of cuts
    # needed for palindrome
    # partitioning of substring str[i..j]
    # P[i][j] = true if substring str[i..j]
    # is palindrome, else false. Note that
    # C[i][j] is 0 if P[i][j] is true
    C = [[0 for i in range(n)]
         for i in range(n)]
    P = [[False for i in range(n)]
         for i in range(n)]
 
    # different looping variables
    j = 0
    k = 0
    L = 0
 
    # Every substring of length
    # 1 is a palindrome
    for i in range(n):
        P[i][i] = True
        C[i][i] = 0
 
    # L is substring length. Build the
    # solution in bottom-up manner by
    # considering all substrings of
    # length starting from 2 to n.
    # The loop structure is the same as
    # Matrix Chain Multiplication problem
    for L in range(2, n + 1):
 
        # For substring of length L, set
        # different possible starting indexes
        for i in range(n - L + 1):
            j = i + L - 1  # Set ending index
 
            # If L is 2, then we just need to
            # compare two characters. Else
            # need to check two corner characters
            # and value of P[i + 1][j-1]
            if L == 2:
                P[i][j] = (str[i] == str[j])
            else:
                P[i][j] = ((str[i] == str[j]) and
                           P[i + 1][j - 1])
 
            # IF str[i..j] is palindrome,
            # then C[i][j] is 0
            if P[i][j] == True:
                C[i][j] = 0
            else:
 
                # Make a cut at every possible
                # location starting from i to j,
                # and get the minimum cost cut.
                C[i][j] = 100000000
                for k in range(i, j):
                    C[i][j] = min(C[i][j], C[i][k] +
                                  C[k + 1][j] + 1)
 
    # Return the min cut value for
    # complete string. i.e., str[0..n-1]
    return C[0][n - 1]
 
 
# Driver code
str = "ababbbabbababa"
print('Min cuts needed for Palindrome Partitioning is',
      minPalPartion(str))
 
# This code is contributed
# by Sahil shelangia


Output

Min cuts needed for Palindrome Partitioning is 3

Time Complexity: O(n3)
Auxiliary Space: O(n2)

Dynamic Programming Approach for Palindrome Partitioning in (O(n2)):

The problem can be solved by finding the suffix starting from j and ending at index i, (1 <= j <= i <= n – 1), which are palindromes. Hence, we can make a cut here that requires 1 + min cut from rest substring [0, j – 1]. For all such palindromic suffixes starting at j and ending at i, keep minimising in minCutDp[i]. Similarly, we need to compute results for all such i. (1 <= i <= n – 1) and finally, minCutDp[n – 1] will be the minimum number of cuts needed for palindrome partitioning of the given string.

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
// Function to generate all possible palindromic substring
bool generatePalindrome(string& s,
                        vector<vector<bool> >& pal)
{
    int n = s.size();
 
    // Initialize the palindrome matrix for single
    // characters
    for (int i = 0; i < n; i++) {
        pal[i][i] = true;
    }
 
    // Iterate over different lengths of substrings
    for (int len = 2; len <= n; len++) {
        // Iterate over the starting positions of substrings
        // of current length
        for (int i = 0; i <= n - len; i++) {
 
            // Calculate the ending position of the
            // substring
            int j = i + len - 1;
 
            // Check if the characters at the starting and
            // ending positions are equal and if the
            // substring between them is a palindrome or a
            // single character
            if (s[i] == s[j]
                && (len == 2 || pal[i + 1][j - 1])) {
 
                // Mark the substring from i to j as a
                // palindrome
                pal[i][j] = true;
            }
        }
    }
}
 
// Function to calculate the minimum number of cuts required
// to make all substrings of 's' palindromic
int minCut(string s)
{
    if (s.empty())
        return 0;
    int n = s.size();
 
    // 2D vector to store whether substring [i, j] is a
    // palindrome
    vector<vector<bool> > pal(n, vector<bool>(n, false));
 
    generatePalindrome(s, pal);
 
    // vector to store minimum cuts required to make
    // substring [i, n-1] palindromic
    vector<int> minCutDp(n, INT_MAX);
 
    // There is no cut required for single character
    // as it is always palindrome
    minCutDp[0] = 0;
 
    // Iterate over the given string
    for (int i = 1; i < n; i++) {
 
        // Check if string 0 to i is palindrome.
        // Then minCut require will be 0.
        if (pal[0][i]) {
            minCutDp[i] = 0;
        }
        else {
            for (int j = i; j >= 1; j--) {
 
                // If s[i] and s[j] are equal and the inner
                // substring [i+1, j-1] is a palindrome or
                // it has a length of 1
                if (pal[j][i]) {
 
                    // Update the minimum cuts required if
                    // cutting at position 'j+1' results in
                    // a smaller value
                    if (minCutDp[j - 1] + 1 < minCutDp[i])
                        minCutDp[i] = minCutDp[j - 1] + 1;
                }
            }
        }
    }
 
    // Return the minimum cuts required for the entire
    // string 's'
    return minCutDp[n - 1];
}
 
int main()
{
    string str = "ababbbabbababa";
 
    int cuts = minCut(str);
    cout << "Minimum cuts required: " << cuts << endl;
    return 0;
}


Java




import java.util.Arrays;
 
public class GFG {
 
    // Function to generate all possible palindromic
    // substrings
    static boolean generatePalindrome(String s,
                                      boolean[][] pal)
    {
        int n = s.length();
 
        // Initialize the palindrome matrix for single
        // characters
        for (int i = 0; i < n; i++) {
            pal[i][i] = true;
        }
 
        // Iterate over different lengths of substrings
        for (int len = 2; len <= n; len++) {
            // Iterate over the starting positions of
            // substrings of current length
            for (int i = 0; i <= n - len; i++) {
 
                // Calculate the ending position of the
                // substring
                int j = i + len - 1;
 
                // Check if the characters at the starting
                // and ending positions are equal and if the
                // substring between them is a palindrome or
                // a single character
                if (s.charAt(i) == s.charAt(j)
                    && (len == 2 || pal[i + 1][j - 1])) {
 
                    // Mark the substring from i to j as a
                    // palindrome
                    pal[i][j] = true;
                }
            }
        }
 
        return true;
    }
 
    // Function to calculate the minimum number of cuts
    // required to make all substrings of 's' palindromic
    static int minCut(String s)
    {
        if (s.isEmpty())
            return 0;
        int n = s.length();
 
        // 2D array to store whether substring [i, j] is a
        // palindrome
        boolean[][] pal = new boolean[n][n];
 
        generatePalindrome(s, pal);
 
        // Array to store minimum cuts required to make
        // substring [i, n-1] palindromic
        int[] minCutDp = new int[n];
        Arrays.fill(minCutDp, Integer.MAX_VALUE);
 
        // There is no cut required for single character
        // as it is always palindrome
        minCutDp[0] = 0;
 
        // Iterate over the given string
        for (int i = 1; i < n; i++) {
 
            // Check if string 0 to i is palindrome.
            // Then minCut require will be 0.
            if (pal[0][i]) {
                minCutDp[i] = 0;
            }
            else {
                for (int j = i; j >= 1; j--) {
 
                    // If s[i] and s[j] are equal and the
                    // inner substring [i+1, j-1] is a
                    // palindrome or it has a length of 1
                    if (pal[j][i]) {
 
                        // Update the minimum cuts required
                        // if cutting at position 'j+1'
                        // results in a smaller value
                        if (minCutDp[j - 1] + 1
                            < minCutDp[i])
                            minCutDp[i]
                                = minCutDp[j - 1] + 1;
                    }
                }
            }
        }
 
        // Return the minimum cuts required for the entire
        // string 's'
        return minCutDp[n - 1];
    }
 
    public static void main(String[] args)
    {
        String str = "ababbbabbababa";
 
        int cuts = minCut(str);
        System.out.println("Minimum cuts required: "
                           + cuts);
    }
}


C#




using System;
 
class Program {
    // Function to generate all possible palindromic
    // substrings
    static void GeneratePalindrome(string s, bool[, ] pal)
    {
        int n = s.Length;
 
        // Initialize the palindrome matrix for single
        // characters
        for (int i = 0; i < n; i++) {
            pal[i, i] = true;
        }
 
        // Iterate over different lengths of substrings
        for (int len = 2; len <= n; len++) {
            // Iterate over the starting positions of
            // substrings of current length
            for (int i = 0; i <= n - len; i++) {
                // Calculate the ending position of the
                // substring
                int j = i + len - 1;
 
                // Check if the characters at the starting
                // and ending positions are equal and if the
                // substring between them is a palindrome or
                // a single character
                if (s[i] == s[j]
                    && (len == 2 || pal[i + 1, j - 1])) {
                    // Mark the substring from i to j as a
                    // palindrome
                    pal[i, j] = true;
                }
            }
        }
    }
 
    // Function to calculate the minimum number of cuts
    // required to make all substrings of 's' palindromic
    static int MinCut(string s)
    {
        if (string.IsNullOrEmpty(s))
            return 0;
        int n = s.Length;
 
        // 2D array to store whether substring [i, j] is a
        // palindrome
        bool[, ] pal = new bool[n, n];
 
        GeneratePalindrome(s, pal);
 
        // Array to store minimum cuts required to make
        // substring [i, n-1] palindromic
        int[] minCutDp = new int[n];
        for (int i = 0; i < n; i++) {
            minCutDp[i] = int.MaxValue;
        }
 
        // There is no cut required for single character as
        // it is always a palindrome
        minCutDp[0] = 0;
 
        // Iterate over the given string
        for (int i = 1; i < n; i++) {
            // Check if string 0 to i is a palindrome. Then
            // minCut required will be 0.
            if (pal[0, i]) {
                minCutDp[i] = 0;
            }
            else {
                for (int j = i; j >= 1; j--) {
                    // If s[i] and s[j] are equal and the
                    // inner substring [i+1, j-1] is a
                    // palindrome or it has a length of 1
                    if (pal[j, i]) {
                        // Update the minimum cuts required
                        // if cutting at position 'j+1'
                        // results in a smaller value
                        if (minCutDp[j - 1] + 1
                            < minCutDp[i])
                            minCutDp[i]
                                = minCutDp[j - 1] + 1;
                    }
                }
            }
        }
 
        // Return the minimum cuts required for the entire
        // string 's'
        return minCutDp[n - 1];
    }
 
    static void Main()
    {
        string str = "ababbbabbababa";
 
        int cuts = MinCut(str);
        Console.WriteLine("Minimum cuts required: " + cuts);
    }
}


Javascript




// JavaScript Code for the above approach
 
function generatePalindrome(s, pal) {
    const n = s.length;
 
    // Initialize the palindrome matrix for single characters
    for (let i = 0; i < n; i++) {
        pal[i][i] = true;
    }
 
    // Iterate over different lengths of substrings
    for (let len = 2; len <= n; len++) {
        // Iterate over the starting positions of substrings of current length
        for (let i = 0; i <= n - len; i++) {
            // Calculate the ending position of the substring
            const j = i + len - 1;
 
            // Check if the characters at the starting and ending positions are equal
            // and if the substring between them is a palindrome or a single character
            if (s[i] === s[j] && (len === 2 || pal[i + 1][j - 1])) {
                // Mark the substring from i to j as a palindrome
                pal[i][j] = true;
            }
        }
    }
}
 
function minCut(s) {
    if (!s) return 0;
    const n = s.length;
 
    // 2D array to store whether substring [i, j] is a palindrome
    const pal = Array.from({ length: n }, () => Array(n).fill(false));
 
    generatePalindrome(s, pal);
 
    // Array to store the minimum cuts required to make substring [i, n-1] palindromic
    const minCutDp = Array(n).fill(Infinity);
 
    // There is no cut required for single character as it is always a palindrome
    minCutDp[0] = 0;
 
    // Iterate over the given string
    for (let i = 1; i < n; i++) {
        // Check if string 0 to i is a palindrome
        // Then minCut required will be 0.
        if (pal[0][i]) {
            minCutDp[i] = 0;
        } else {
            for (let j = i; j >= 1; j--) {
                // If s[i] and s[j] are equal and the inner substring [i+1, j-1]
                // is a palindrome or it has a length of 1
                if (pal[j][i]) {
                    // Update the minimum cuts required if cutting at position 'j+1' results in a smaller value
                    if (minCutDp[j - 1] + 1 < minCutDp[i]) {
                        minCutDp[i] = minCutDp[j - 1] + 1;
                    }
                }
            }
        }
    }
 
    // Return the minimum cuts required for the entire string 's'
    return minCutDp[n - 1];
}
 
const str = "abbac";
const cuts = minCut(str);
document.write("Minimum cuts required:", cuts);
 
// This code is contributed by Abhinav Mahajan (abhinav_m22)


Python3




def generate_palindrome(s, pal):
    n = len(s)
 
    # Initialize the palindrome matrix for single characters
    for i in range(n):
        pal[i][i] = True
 
    # Iterate over different lengths of substrings
    for length in range(2, n + 1):
        # Iterate over the starting positions of substrings of current length
        for i in range(n - length + 1):
            # Calculate the ending position of the substring
            j = i + length - 1
 
            # Check if the characters at the starting and ending positions are equal
            # and if the substring between them is a palindrome or a single character
            if s[i] == s[j] and (length == 2 or pal[i + 1][j - 1]):
                # Mark the substring from i to j as a palindrome
                pal[i][j] = True
 
 
def min_cut(s):
    if not s:
        return 0
    n = len(s)
 
    # 2D list to store whether substring [i, j] is a palindrome
    pal = [[False] * n for _ in range(n)]
 
    generate_palindrome(s, pal)
 
    # List to store minimum cuts required to make substring [i, n-1] palindromic
    min_cut_dp = [float('inf')] * n
 
    # There is no cut required for a single character as it is always a palindrome
    min_cut_dp[0] = 0
 
    # Iterate over the given string
    for i in range(1, n):
        # Check if string 0 to i is a palindrome. Then minCut required will be 0.
        if pal[0][i]:
            min_cut_dp[i] = 0
        else:
            for j in range(i, 0, -1):
                # If s[i] and s[j] are equal and the inner substring [i+1, j-1]
                # is a palindrome or it has a length of 1
                if pal[j][i]:
                    # Update the minimum cuts required if cutting at position 'j+1' results in a smaller value
                    if min_cut_dp[j - 1] + 1 < min_cut_dp[i]:
                        min_cut_dp[i] = min_cut_dp[j - 1] + 1
 
    # Return the minimum cuts required for the entire string 's'
    return min_cut_dp[n - 1]
 
 
# Driver code
if __name__ == "__main__":
    str = "ababbbabbababa"
 
    cuts = min_cut(str)
    print("Minimum cuts required:", cuts)


Output

Minimum cuts required: 3

Time Complexity: O(n2)
Auxiliary Space: O(n2)



Previous Article
Next Article

Similar Reads

Count all palindrome which is square of a palindrome
Given two positive integers L and R (represented as strings) where [Tex]1\leq L \leq R\leq10^{18} [/Tex]. The task is to find the total number of super-palindromes in the inclusive range [L, R]. A palindrome is called super-palindrome if it is a palindrome and also square of a palindrome. Examples: Input: L = "4", R = "1000" Output: 4 Explanation:
10 min read
Sentence Palindrome (Palindrome after removing spaces, dots, .. etc)
Write a program to check if a sentence is a palindrome or not. You can ignore white spaces and other characters to consider sentences as a palindrome. Examples: Input : str = "Too hot to hoot." Output : Sentence is palindrome. Input : str = "Abc def ghi jklm." Output : Sentence is not palindrome. Note: There may be multiple spaces and/or dots betwe
12 min read
Minimize the cost of partitioning an array into K groups
Given an array arr[] and an integer K, the task is to partition the array into K non-empty groups where each group is a subarray of the given array and each element of the array is part of only one group. All the elements in a given group must have the same value. You can perform the following operation any number of times: Choose an element from t
15+ min read
Binary Space Partitioning
Binary Space Partitioning is implemented for recursively subdividing a space into two convex sets by using hyperplanes as partitions. This process of subdividing gives rise to the representation of objects within the space in the form of tree data structure known as BSP Tree. Binary space partitioning arose in the context of 3D computer graphics in
4 min read
Three way partitioning using Dutch National Sort Algorithm(switch-case version) in Java
Given an array list arr and values lowVal and highVal. The task is to partition the array around the range such that the array List is divided into three parts. 1) All elements smaller than lowVal come first.2) All elements in range lowVal to highVVal come next.3) All elements greater than highVVal appear in the end.The individual elements of three
4 min read
Javascript Program For Partitioning A Linked List Around A Given Value And Keeping The Original Order
Given a linked list and a value x, partition it such that all nodes less than x come first, then all nodes with a value equal to x, and finally nodes with a value greater than or equal to x. The original relative order of the nodes in each of the three partitions should be preserved. The partition must work in place.Examples: Input: 1->4->3-
4 min read
Three way partitioning of an Array without changing the relative ordering
Given an array and a range [lowVal, highVal], partition the array around the range such that the array is divided into three parts. All elements smaller than lowVal come first. All elements in range lowVal to highVal come next. All elements greater than highVVal appear in the end. The relative ordering of numbers shouldn't be changed. Examples: Inp
9 min read
Find maximum subset sum formed by partitioning any subset of array into 2 partitions with equal sum
Given an array A containing N elements. Partition any subset of this array into two disjoint subsets such that both the subsets have an identical sum. Obtain the maximum sum that can be obtained after partitioning. Note: It is not necessary to partition the entire array, that is any element might not contribute to any of the partition. Examples: In
15+ min read
POTD Solutions | 24 Oct’ 23 | Palindromic Partitioning
View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Dynamic Programming but will also help you build up problem-solving skills. We recommend you to try this
6 min read
String Partitioning for Character Equality
Given a string S of size N, the task is to divide the given string into two non-empty strings s1 and s2 such that the number of distinct characters in s1 is equal to s2. Examples: Input: s = "aacaba"Output: 2Explanation: => Dividing s into s1 and s2 as ("aac", "aba"), the left string contains 2 distinct letters, and the right string also contain
7 min read
Binary String Partitioning
Given a Binary String S consisting of N bits, integers K and D. The task is to determine whether the maximum absolute difference among all K disjoint strings in S can be made less than D. Note: Some of the K strings can be empty, and each character of S can only belong to one of the K strings Examples: Input: N = 6, K = 2, D = 5, S = "110001"Output
5 min read
Clustering/Partitioning an array such that sum of square differences is minimum
Given an array of n numbers and a number k. We need to divide the array into k partitions (clusters) of the same or different lengths. For a given k, there can be one or more ways to make clusters (partitions). We define a function Cost(i) for the ith cluster, as the square of the difference between its first and last element. If the current cluste
15 min read
Partitioning a linked list around a given value and If we don't care about making the elements of the list "stable"
Given a linked list and a value x, partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. If x is contained within the list the values of x only need to be after the elements less than x (see below). The partition element x can appear anywhere in the "right partition"; it does not
8 min read
Minimum Subset sum difference problem with Subset partitioning
Given a set of N integers with up to 40 elements, the task is to partition the set into two subsets of equal size (or the closest possible), such that the difference between the sums of the subsets is minimized. If the size of the set is odd, one subset will have one more element than the other. If the size is even, both subsets will have the same
13 min read
Minimizing Removal of Characters for Partitioning into three substrings that contain 'a' and 'b' characters only.
Given a string S of length N, find the minimum characters we need to remove such that the resultant string can be cut into 3 strings (possibly empty) without changing the order of letters, where the first and the third string contains only letter "a" and second string contains only "b". Examples: Input: S = "bab"Output: 1Explanation: We can remove
7 min read
Find the minimum cost of partitioning the given string S into contiguous substrings
Given a string S and an array of strings arr[]. The task is to find the minimum cost of partitioning the given string S into continuous substrings. If a substring is present in arr[] then the cost of partition would be 0, otherwise, the cost would be the length of that substring. Examples: Input: S = geeksforgeeks, A[] = {geek, for}Output: 2Explana
7 min read
Three way partitioning of an array around a given range
Given an array and a range [lowVal, highVal], partition the array around the range such that array is divided in three parts. All elements smaller than lowVal come first. All elements in range lowVal to highVal come next. All elements greater than highVal appear in the end. The individual elements of the three sets can appear in any order. Examples
7 min read
Maximizing GCD by Partitioning a Number into K Parts
Given a number N, break the number into K positive integers a1, a2, a3 .... aK such that a1 + a2 + a3 .... aK = N. The task is to maximize the GCD(a1, a2, a3 .... aK). Examples: Input: N = 420, K = 69 Output: 6Explanation: We can break 420 into 68 integers of value 6 and 1 integer of value 12. Therefore, the max GCD is 6. Input: N = 5, K = 5 Output
7 min read
Partitioning a linked list around a given value and keeping the original order
Given a linked list and a value x, partition it such that all nodes less than x come first, then all nodes with a value equal to x, and finally nodes with a value greater than x. The original relative order of the nodes in each of the three partitions should be preserved. Examples: Input : 1 -> 4 -> 3 -> 2 -> 5 -> 2 -> 3, x = 3Out
9 min read
Minimum cost to convert the given String into Palindrome
Given a string S of length N and 2 integers X and Y, the task is to find the minimum cost of converting the string to a palindrome by performing the following operations any number of times in any order: Move the leftmost character to the rightmost end of the string at cost X. i.e S1S2...SN gets converted into S2S3...SNS1.Replace any character of t
15+ min read
Minimum cost to convert string into palindrome
Convert string S into a palindrome string. You can only replace a character with any other character. When you replace character 'a' with any other character, it costs 1 unit, similarly for 'b' it is 2 units ..... and for 'z', it is 26 units. Find the minimum cost required to convert string S into palindrome string. Examples : Input : abcdef Output
4 min read
Binary String of given length that without a palindrome of size 3
Given an integer n. Find a string of characters 'a' and 'b' such that the string doesn't contain any palindrome of length 3. Examples: Input : 3 Output : "aab" Explanation: aab is not a palindrome. Input : 5 Output : aabba Explanation: aabba does not contain a palindrome of size 3. The approach here is that we can use this string 'aabb' and print t
3 min read
Next word that does not contain a palindrome and has characters from first k
Given a string and a limit k, find lexicographically next word which contains characters from a set of first K letters of the English alphabet and does not contain a palindrome as it's substring of length more than one. It may be assumed that the input string does not contain a palindromic substring. Examples: Input : s = "cba" k = 4 Output : cbd I
7 min read
Sum of first K even-length Palindrome numbers
Given a integer k, find the sum of first k even-length palindrome numbers. Even length here refers to the number of digits of a number is even. Examples: Input : k = 3 Output : 66 Explanation: 11 + 22 + 33 = 66 (Sum of first three even-length palindrome numbers) Input : 10 Output : 1496 Explanation: 11+22+33+44+55+66+77+88+ 99+1001 = 1496 A naive a
9 min read
Minimum number of deletions to make a string palindrome | Set 2
Given a string A, compute the minimum number of characters you need to delete to make resulting string a palindrome. Examples: Input : baca Output : 1 Input : geek Output : 2 We have discussed one approach in below post. Minimum number of deletions to make a string palindrome Below approach will use modified Levenshtein distance. We consider modifi
9 min read
Make a lexicographically smallest palindrome with minimal changes
Given a string S. Print the lexicographically smallest string possible. You can make minimal changes to the characters in the string and you can permute the string. Examples: Input : S = "aabc" Output : "abba" Input : S = "aabcd" Output : "abcba" Explanation 1:Change the last index "c" to "b", it becomes "aabb". Then rearrange the string, it become
11 min read
Convert the string into palindrome string by changing only one character
Given a string str. Check if it is possible to convert the string into palindrome string by changing only one character.Examples: Input : str = "abccaa" Output : Yes We can change the second last character i.e. 'a' to 'b' to make it palindrome string Input : str = "abbcca" Output : No We can not convert the string into palindrome string by changing
5 min read
Find if string is K-Palindrome or not using all characters exactly once
Given a string str and an integer K, the task is to check if it is possible to make the string K palindromes using all the characters of the string exactly once.Examples: Input: str = "poor", K = 3 Output: Yes One way of getting 3 palindromes is: oo, p, rInput: str = "fun", K = 5 Output: No 2 palindromes can't be constructed using 3 distinct letter
6 min read
Bash program to check if the Number is a Palindrome
Given a number num, find whether the given number is palindrome or not using Bash Scripting. Examples: Input : 666 Output : Number is palindrome Input : 45667 Output : Number is NOT palindrome Approach To find the given number is palindrome just check if the number is same from beginning and the end. Reverse the number to check if the number revers
1 min read
Rearrange characters to form palindrome if possible
Given a string, convert the string to palindrome without any modifications like adding a character, removing a character, replacing a character etc. Examples: Input : "mdaam" Output : "madam" or "amdma" Input : "abb" Output : "bab" Input : "geeksforgeeks" Output : "No Palindrome"Count occurrences of all characters. Count odd occurrences. If this co
7 min read