VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-minimum-number-of-non-palindromic-partition-of-binary-array/

⇱ Find minimum number of non palindromic partition of Binary Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find minimum number of non palindromic partition of Binary Array

Last Updated : 19 Dec, 2022

Given a binary array A[] of length 2*N, the task is to find the minimum number of partitions that follow the below conditions:

  • Each array element belongs to exactly one partition
  • None of the partitioned subarrays is a palindrome

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:

  • Check whether an array is a palindrome or not and if the array is not a palindrome then print 1.
  • After that check whether array A[] consists of only 0's or only 1's as an element and if it is true then print -1.
  • Otherwise, print 2 as an answer for the number of partitions of an array that satisfy conditions.

Below is the implementation of the above approach.


Output
2

Time Complexity: O(N)
Auxiliary Space: O(1)

Comment
Article Tags: