Site Message
Only Premium Users can view the Question
<h2>About Coding Round</h2>
<h3>Problem 3 (5 marks)</h3> Minimum no of cuts to make all substring palindromic.<br> <pre> Example Input: geek <br> Example Output: 2 <br> Explanation: g ee k (2 cuts required)<br></pre>
Overview
Solution
cut[j-1]+1
, 1 stands for 1 cut in between j-1 and j and cut[j-1] stands for minimum cut up to j-1.Time Complexity : O(n*n)
Code
ll n;
cin >> n;
string s;
cin >> s;
ll cut[n]; // declare an array cut denoting minimum cuts required till index i
bool palindrome[n][n]; // initialize a 2-d array named palindrome with false which denotes if index i to j is a palindrome or not
memset(palindrome, false, sizeof(palindrome));
for (ll i = 0; i < n; i++)
{
ll minCut = i; // initialize a variable minCut as the length of current prefix-1 which is the maximum value
for (ll j = 0; j <= i; j++)
{
if (s[i] == s[j] && (i - j < 2 || palindrome[j + 1][i - 1])) // now we know the value of cut[j] for all j less than i
{
palindrome[j][i] = true; // now if the string from j to i is a palindrome
minCut = min(minCut, j == 0 ? 0 : (cut[j - 1] + 1)); // In cut[j-1]+1, 1 stands for 1 cut in between j-1 and j and cut[j-1] stands for minimum cut upto j-1
}
}
cut[i] = minCut; // assign minCut to cut[i] which is minimum cut required upto index i
}
cout << cut[n - 1] << endl; // print the required answer