Tutorialspoint
Problem
Solution
Submissions

Palindrome Partitioning II

Certification: Advanced Level Accuracy: 100% Submissions: 1 Points: 15

Write a Java program to find the minimum number of cuts needed to partition a string such that every substring of the partition is a palindrome. A palindrome is a string that reads the same backward as forward.

Example 1
  • Input: s = "aab"
  • Output: 1
  • Explanation: We need to partition the string "aab" into palindromic substrings. One possible partition is ["aa", "b"], which requires 1 cut. Both "aa" and "b" are palindromes.
Example 2
  • Input: s = "abccbc"
  • Output: 2
  • Explanation: We need to partition the string "abccbc" into palindromic substrings. One possible partition is ["a", "b", "ccbc"], which requires 2 cuts. All substrings "a", "b", and "ccbc" are palindromes.
Constraints
  • 1 ≤ s.length ≤ 2000
  • s consists of lowercase English letters only
  • Time Complexity: O(n²) where n is the length of the string
  • Space Complexity: O(n²)
StringsDynamic Programming GoogleFacebook
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 approach to solve this problem
  • Create a 2D boolean array to keep track of whether substring s[i...j] is a palindrome
  • Create a 1D array to store the minimum cuts needed for substring s[0...i]
  • For each position i, check all possible substrings ending at i
  • If a substring s[j...i] is a palindrome, update the minimum cuts
  • Be careful of the base case where the entire string is already a palindrome

Steps to solve by this approach:

 Step 1: Create a 2D boolean array isPalindrome[n][n] to identify if substring s[start...end] is a palindrome.

 Step 2: Create a 1D array minCuts[n] to store the minimum cuts needed for substring s[0...i]. Initialize each minCuts[i] with i.
 Step 3: Fill the isPalindrome table by checking all possible substrings.
 Step 4: For each end position, check all possible start positions to see if s[start...end] is a palindrome.
 Step 5: If s[start...end] is a palindrome and starts from index 0, no cuts needed up to end index.
 Step 6: If s[start...end] is a palindrome but doesn't start from index 0, calculate minimum cuts as minCuts[start-1] + 1.
 Step 7: The final answer is minCuts[n-1], representing the minimum cuts for the whole string.

Submitted Code :