Open In App

Find minimum number of non palindromic partition of Binary Array

Last Updated : 19 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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.

C++




// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if the array is palindrome
bool isPalindrome(int arr[], int n)
{
  int flag = 0;
 
  // Loop till array size n/2.
  for (int i = 0; i <= n / 2 && n != 0; i++) {
 
    if (arr[i] != arr[n - i - 1]) {
      flag = 1;
      break;
    }
  }
 
  if (flag == 1)
    return false;
  else
    return true;
}
 
// Function to find number of
// partitions of an array
void numOfPartition(int arr[], int n)
{
  if (!isPalindrome(arr, n)) {
    cout << 1;
  }
  else {
    int k = 0, z = 0;
    for (int i = 0; i < n; i++) {
      if (arr[i] == 0)
        z++;
      else
        k++;
    }
    if (k == 0 || z == 0) {
      cout << -1;
    }
    else {
      cout << 2;
    }
  }
}
 
// Driver Code
int main()
{
  int A[] = { 1, 0, 1, 1, 0, 1 };
  int N = sizeof(A) / sizeof(A[0]);
 
  // Function call
  numOfPartition(A, N);
 
  return 0;
}
 
// This code is contributed by aarohirai2616.


Java




// Java code to implement the approach
 
import java.io.*;
import java.util.*;
 
public class GFG {
 
    // Function to find number of
    // partitions of an array
    public static void numOfPartition(int arr[], int n)
    {
        if (!isPalindrome(arr, n)) {
            System.out.println(1);
        }
        else {
            int k = 0, z = 0;
            for (int i = 0; i < n; i++) {
                if (arr[i] == 0)
                    z++;
                else
                    k++;
            }
            if (k == 0 || z == 0) {
                System.out.println(-1);
            }
            else {
                System.out.println(2);
            }
        }
    }
 
    // Function to check if the array is palindrome
    static boolean isPalindrome(int arr[], int n)
    {
        int flag = 0;
 
        // Loop till array size n/2.
        for (int i = 0; i <= n / 2 && n != 0; i++) {
 
            if (arr[i] != arr[n - i - 1]) {
                flag = 1;
                break;
            }
        }
 
        if (flag == 1)
            return false;
        else
            return true;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] A = { 1, 0, 1, 1, 0, 1 };
        int N = A.length;
 
        // Function Call
        numOfPartition(A, N);
    }
}


Python




# Python code to implement the approach
 
# Function to check if the array is palindrome
def isPalindrome(arr, n):
 
    flag = 0
 
    # Loop till array size n/2.
    i = 0
    while(i <= n // 2 and n != 0):
 
        if (arr[i] != arr[n - i - 1]):
            flag = 1
            break
 
        i += 1
 
    if (flag == 1):
        return False
    else:
        return True
 
# Function to find number of
# partitions of an array
def numOfPartition(arr, n):
 
    if (isPalindrome(arr, n) == False):
        print(1)
    else:
        k = 0
        z = 0
        for i in range(0, n):
            if (arr[i] == 0):
                z += 1
            else:
                k += 1
        if (k == 0 or z == 0):
            print(-1)
 
        else:
            print(2)
 
# Driver Code
A = [1, 0, 1, 1, 0, 1]
N = len(A)
 
# Function call
numOfPartition(A, N)
 
# This code is contributed by Samim Hossain Mondal.


C#




// C# code to implement the approach
 
using System;
 
public class GFG {
 
    // Function to find number of
    // partitions of an array
    public static void numOfPartition(int[] arr, int n)
    {
        if (!isPalindrome(arr, n)) {
            Console.WriteLine(1);
        }
        else {
            int k = 0, z = 0;
            for (int i = 0; i < n; i++) {
                if (arr[i] == 0)
                    z++;
                else
                    k++;
            }
            if (k == 0 || z == 0) {
                Console.WriteLine(-1);
            }
            else {
                Console.WriteLine(2);
            }
        }
    }
 
    // Function to check if the array is palindrome
    static bool isPalindrome(int[] arr, int n)
    {
        int flag = 0;
 
        // Loop till array size n/2.
        for (int i = 0; i <= n / 2 && n != 0; i++) {
 
            if (arr[i] != arr[n - i - 1]) {
                flag = 1;
                break;
            }
        }
 
        if (flag == 1)
            return false;
        else
            return true;
    }
 
    static public void Main()
    {
 
        // Code
        int[] A = { 1, 0, 1, 1, 0, 1 };
        int N = A.Length;
 
        // Function Call
        numOfPartition(A, N);
    }
}
 
// This code is contributed by lokesh


Javascript




// Javascript code to implement the approach
 
// Function to check if the array is palindrome
function isPalindrome(arr, n)
{
let flag = 0;
 
// Loop till array size n/2.
for (let i = 0; i <= n / 2 && n != 0; i++) {
 
    if (arr[i] != arr[n - i - 1]) {
    flag = 1;
    break;
    }
}
 
if (flag == 1)
    return false;
else
    return true;
}
 
// Function to find number of
// partitions of an array
function numOfPartition(arr, n)
{
if (!isPalindrome(arr, n)) {
    console.log("1");
}
else {
    let k = 0, z = 0;
    for (let i = 0; i < n; i++) {
    if (arr[i] == 0)
        z++;
    else
        k++;
    }
    if (k == 0 || z == 0) {
    console.log("-1");
    }
    else {
    console.log("2");
    }
}
}
 
// Driver Code
 
let A = [ 1, 0, 1, 1, 0, 1 ];
let N = A.length;
 
// Function call
numOfPartition(A, N);
 
// This code is contributed by Pushpesh Raj.


Output

2

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



Similar Reads

Make palindromic string non-palindromic by rearranging its letters
Given string str containing lowercase alphabets (a - z). The task is to print the string after rearranging some characters such that the string becomes non-palindromic. If it's impossible to make the string non-palindrome then print -1. Examples: Input: str = "abba" Output: aabb Input: str = "zzz" Output: -1 Brute Force: Iterate through all possibl
9 min read
Minimum cuts required to convert a palindromic string to a different palindromic string
Given palindromic string s, the task is to find minimum k, such that you can cut this string into k+1 parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string s. If it is impossible then print -1.Examples: Input : string = "civic" Output : 2 Explanation : ci | v | ic --&gt; ic |
16 min read
Partition a string into palindromic strings of at least length 2 with every character present in a single string
Given a string S consisting of N lowercase alphabets, the task is to check if all the strings of at least length 2 formed by selecting every character of the string S only once are palindromic or not. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: S = "abbbaddzcz"Output: YesExplanation: The palindromic strings of len
10 min read
Minimum toggles to partition a binary array so that it has first 0s then 1s
Given an array of n integers containing only 0 and 1. Find the minimum toggles (switch from 0 to 1 or vice-versa) required such the array become partitioned, i.e., it has first 0s than 1s. There should be at least one 0 in the beginning, and there can be zero or more 1s in the end. Input: arr[] = {1, 0, 1, 1, 0} Output: 2 Toggle the first and last
7 min read
Partition array into two subsets with minimum Bitwise XOR between their maximum and minimum
Given an array arr[] of size N, the task is to split the array into two subsets such that the Bitwise XOR between the maximum of the first subset and minimum of the second subset is minimum. Examples: Input: arr[] = {3, 1, 2, 6, 4} Output: 1 Explanation: Splitting the given array in two subsets {1, 3}, {2, 4, 6}. The maximum of the first subset is
5 min read
Split an array into minimum number of non-increasing or non-decreasing subarrays
Given an array arr[] of size N, the task is to split the given array into a minimum number of subarrays such that elements of each subarray are either in non-increasing order or non-decreasing order. Examples: Input: arr[] = {2, 3, 9, 5, 4, 6, 8}Output: 3Explanation: Split the array into 3 subarrays following three subarrays: {2, 3, 9} (non-decreas
10 min read
Partition string into two substrings having maximum number of common non-repeating characters
Given a string str, the task is to find the maximum count of common non-repeating characters that can be obtained by partitioning the given string into two non-empty substrings. Examples: Input : str = "aabbca" Output: 2 Explanation: Partition the string into two substrings { { str[0], ... str[2] }, { str[3], ..., str[5] } } The common non-repeatin
15 min read
Partition an array of non-negative integers into two subsets such that average of both the subsets is equal
Given an array of size N. The task is to partition the given array into two subsets such that the average of all the elements in both subsets is equal. If no such partition exists print -1. Otherwise, print the partitions. If multiple solutions exist, print the solution where the length of the first subset is minimum. If there is still a tie then p
14 min read
Longest Palindromic Substring using Palindromic Tree | Set 3
Given a string, find the longest substring which is a palindrome. For example, if the given string is “forgeeksskeegfor”, the output should be “geeksskeeg”. Prerequisite : Palindromic Tree | Longest Palindromic Substring Structure of Palindromic Tree : The palindromic Tree’s actual structure is close to the directed graph. It is actually a merged s
16 min read
Minimum number of palindromic subsequences to be removed to empty a binary string
Given a binary string, count minimum number of subsequences to be removed to make it an empty string. Examples : Input: str[] = "10001" Output: 1 Since the whole string is palindrome, we need only one removal. Input: str[] = "10001001" Output: 2 We can remove the middle 1 as first removal, after first removal string becomes 1000001 which is a palin
6 min read
Article Tags :
Practice Tags :