![]() |
VOOZH | about |
Given a binary array A[] of length 2*N, the task is to find the minimum number of partitions that follow the below conditions:
Note: If there are multiple answers print anyone that satisfies the above conditions and if no such partition exists that satisfies the above condition then print -1.
Examples:
Input: A[] = {1, 0, 1, 1, 0, 1}
Output: 2
?Explanation: One of the valid partitions of A = {1, 0, 1, 1, 0, 1} is {1, 0} and {1, 1, 0, 1} which satisfy above conditions.Hence we can partition an array into 2 subarrays.Input: A[] = {1, 0, 0, 1, 0, 0, 1, 1}
Output: 1
Explanation: Here A = {1, 0, 0, 1, 0, 0, 1, 1} is itself not a palindrome. Then, no more partitioning needs to be done: just take A itself. Hence number of partitions of an array is 1.
Approach: The problem can be solved based on the following observation:
- A trivial impossible case is when an array A consists of only 0's or only 1's as an element and print -1.
- In every other case, a valid partition exists and only 2 partitions are sufficient.
- Suppose A is itself not a palindrome. Then, no more partitioning needs to be done: just take A itself.
- Now we consider the case when A is a palindrome. Note that the length of A is even.
- Suppose the first half of A is not a palindrome. Then, its second half is also not a palindrome, so simply partition it into these two halves.
- Otherwise, the first N elements of A form a palindrome. In this case, consider the string formed by the first N+1 elements of A: this is definitely not a palindrome.
Follow the below steps to solve the problem:
Below is the implementation of the above approach.
2
Time Complexity: O(N)
Auxiliary Space: O(1)