Test if Binary Array could be made Palindrome by flipping two bits at a time

0
8
Adv1


Adv2

View Dialogue

Enhance Article

Save Article

Like Article

View Dialogue

Enhance Article

Save Article

Like Article

Given a binary array A[] of measurement N, the duty is to test whether or not the array could be transformed right into a palindrome by flipping two bits in every operation.

Be aware: The operation could be carried out any variety of instances.

Examples:

Enter: A[] = {1, 0, 1, 0, 1, 1}
Output: Sure

Clarification: We will carry out the next operation:
Choose i = 2 and j = 4. Then {1, 0, 1, 0, 1, 1}→{1, 0, 0, 0, 0, 1} which is a palindrome.

Enter: A[] = {0, 1}
Output: No

Strategy: The issue could be solved based mostly on the next commentary: 

Depend variety of 0s and 1s. 

  • If the worth of rely of 0s and 1s are odd then no palindrome could be made by performing operation on A[].
  • In any other case, array A[] can transformed right into a palindrome after performing operation on array.

Comply with the under steps to unravel the issue:

  • Set zeros = 0 and ones = 0 to retailer the rely of variety of 0s and 1s within the array.
  • After that iterate a loop from 0 to N-1 equivalent to:
    • If A[i] = 0 increment the worth of zeros in any other case increment the worth of ones.
  • If the worth of zeros and ones is odd then print “No” i.e. it’s not potential to transform A to a palindrome by making use of the above operation any variety of instances.
  • In any other case, print “Sure”.

Under is the implementation of the above strategy.

Java

  

import java.io.*;

import java.util.*;

  

public class GFG {

  

    

    

    public static String test(int arr[], int n)

    {

        int one = 0, zero = 0;

        for (int i = 0; i < n; i++) {

            if (arr[i] == '0') {

                zero++;

            }

            else {

                one++;

            }

        }

        if (one % 2 != 0 && zero % 2 != 0)

            return "No";

        return "Sure";

    }

  

    

    public static void most important(String[] args)

    {

        int[] A = { 1, 0, 1, 0, 1, 1 };

        int N = A.size;

  

        

        System.out.println(test(A, N));

    }

}

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

Adv3