

For the string “abc”, we can create 2 partitions and get 3 palindromic strings "a", "b" and "c".
For the string “abbcb”, we can create 2 partitions and get 3 palindrome strings "a", "b" and "bcb".
The first line of input contains an integer ‘T’ denoting the number of test cases.
The first and only line of each test case contains the string 'STR'.
For each test case, print an integer denoting the minimum number of partitions required such that each partition is a palindrome.
You don’t have to print anything, it has already been taken care of. Just complete the function.
1 <= T <= 10
1 <= | STR | <= 200
STR contains lowercase English alphabets only.
Where ‘T’ is the total number of test cases and | STR | represents the length of the string STR.
Time Limit: 1 sec
We are solving this problem by solving its subproblems and then combining the solutions of those subproblems. If we analyze carefully, we will see that we are solving the same subproblems multiple times. Thus, this problem exhibits overlapping subproblems. Thus, in this approach, we will eliminate the need for solving the same subproblems again and again.
Suppose we have ‘STR’ as “abc”
The below figure shows some of the recursive calls made for the given problem.
As we can see, some subproblems are called multiple times.
The same subproblems are shown by the same color.
That’s why we are storing the solved subproblems in a lookup table so that we don’t have to solve them again. Whenever a call is made to the solved subproblem, we will directly return the answer of that subproblem stored in the lookup table.
This problem can be solved using Dynamic Programming. Follows the steps below to solve this problem:
In the previous approach, we were checking for the palindrome or we were making the cut at every possible location. This step resulted in an additional time consumption of the order O(N), resulting in the time complexity of O((N ^ 2) * N) = O(N ^ 3). Instead of checking for the palindrome in O(N) time, we can check it in O(1) time.
1. Create a 2-D boolean array ‘isPalindrome’ of size ‘N’ * ‘N’.
2. The value ‘isPalindrome[i][j]’ denotes whether the substring ‘STR[i...j]’ is a palindrome or not.
3. Now, to calculate ‘isPalindrome[i][j]’, just check ‘isPalindrome[i + 1][j - 1]’ and the corner characters, ‘STR[i]’ and ‘STR[j]’.
‘isPalindrome[i][j]’ will be “True” if ‘STR[i]’ is equal to ‘STR[j]’ and ‘isPalindrome[i + 1][j - 1]’ is “true”. Else, it will be “False”.
The final time complexity can be reduced from O(N ^ 3) to O(N ^ 2), by precomputing the ‘isPalindromic’ matrix in O(N ^ 2) and then filling the ‘CUTS’ array in O(N ^ 2).
Create a 1-D array ‘CUTS’ of size (N), where ‘CUTS[i]’ stores the minimum number of cuts required for palindromic partitioning of substring ‘STR[0..i]’.
Note that L1 and L2 are two nested loops.