...

/

Palindromic Partitioning

Palindromic Partitioning

Let's solve the Palindromic Partitioning problem using Dynamic Programming.

Statement

Suppose you are given a string, s. You need to perform the minimum number of cuts to divide the string into substrings, such that all the resulting substrings are palindromes.

Let’s say you have the following string:

  • “apple”

The resulting substrings after performing the minimum number of cuts are:

  • “a”|“pp”|“l”|“e”

So, a minimum of 33 cuts are required.

Constraints:

  • 11 \leq s.length 1.5×103\leq 1.5\times10^3
  • s consists of only lowercase English characters.

Examples

No.

s

cuts

1

"sleek"

3

2

"adjacent"

7

3

"radar"

0

Try it yourself

Implement your solution in the following coding playground.

Press + to interact
Java
usercode > MinCuts.java
import java.util.*;
public class MinCuts {
public static int minCuts(String arr) {
// Write your code here
return -1;
}
}
Palindromic Partitioning

Note: If you clicked the “Submit” button and the code timed out, this means that your solution needs to be optimized in terms of running time.

Hint: Use dynamic programming and see the magic.

Solution

We will first explore the naive recursive solution to this problem and then see how it can be improved using the Palindromic Subsequence dynamic programming pattern.

Naive approach

A naive approach would be to generate combinations of all possible cuts that can be placed on the string such that all the resulting substrings are palindromes. We will then select the minimum number of cuts.

For example, we have the following string:

s: “abac”

To find the minimum number of cuts, we try all possible combinations:

  • “a” |“b” |“a” |“c” —
...