Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Check if given Array can be made a binary Array with K consecutive 1s
Next article icon

Check if Binary Array can be made palindrome after K bitwise XOR with 1

Last Updated : 14 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a binary array arr[] of size N and an integer K, the task is to check whether the binary array can be turned into a palindrome after K number of operations where in one operation, any random index can be chosen and the value stored in the index will be replaced by its bitwise XOR(^) with1.

Examples:

Input: arr[] = { 1, 0, 0, 1, 1}, K = 0
Output: No
Explanation: As the array is not a palindrome, we must need some non-zero number of operations
to make it palindrome.

Input: arr[] = { 1, 0, 1, 1, 0, 0}, K = 1
Output: Yes
Explanation: Closest arrays which are palindrome : {0, 0, 1, 1, 0, 0} and {1, 0, 1, 1, 0, 1}, which is possible
using 1 such operations only.

 

Approach: The approach to solve the problem is based on the following idea:

The minimum number of operations required is the number of unequal elements equidistant from the mid of the array and to make them equal it takes 1 operation (from 1 to 0 or from 0 to 1).
There is need of 2 operations to change two equal elements and make them have the same value again using bitwise XOR.

To implement this idea, follow the steps shown below :

  • Initialize two pointers pointing at the two ends of the array. 
  • Find the number of unequal array elements while traversing the array from its two ends.
  • If the number is greater than K, then it is impossible to reach the target with exactly K steps.
  • If the number is exactly equal to K, then it is possible to make the array palindrome.
  • Otherwise, if the number is lesser than K:
    • If the array length is odd, then any number of positive K is fine as we can perform the operations at the mid index.  
    • If the array length is even, to keep it a palindrome, we must choose two indices and make the operations on those indices. So remaining K has to be even.

Here is the code for the above approach:

C++




// C++ code for the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check whether the array
// can be turned into palindrome after K
// number of operations
bool check_possibility(int* arr, int K)
{
    // Store the length of the array in
    // arr_length variable
    int arr_length = sizeof(arr) / sizeof(
                                       arr[0]);
 
    // Initialize two pointers from left and
    // right ends of the array
    int i = 0;
    int j = arr_length - 1;
 
    // Keep iterating through the array from
    // two ends until the two pointers cross
    // each other to count the number
    // of the different array items.
    while (i < j) {
 
        // If the two elements are unequal,
        // decrease the value of K by one
        if (arr[i] != arr[j]) {
            K--;
        }
 
        // Move the left pointer towards the
        // right and right pointer towards the
        // left
        i++;
        j--;
    }
 
    // The unequal items are more than K or K
    // becomes less than zero, it is impossible
    // to make it a palindrome with D operations.
    if (K < 0) {
        return false;
    }
 
    // If K has a non-negative value, we make the
    // array a palindrome if it has an odd length
    // the remaining value of K is odd as we have
    // to choose two indices at a time to keep it
    // as a palindrome.
    else {
        if ((arr_length % 2) != 0
            || (K % 2) == 0) {
            return true;
        }
        else {
            return false;
        }
    }
}
 
// Driver code
int main()
{
    int arr[6] = { 1, 0, 1, 1, 0, 0 };
    int K = 1;
 
    // Function call
    if (check_possibility(arr, K) == true) {
        cout << "Yes" << endl;
    }
    else {
        cout << "No" << endl;
    }
    return 0;
}
 
 

Java




// Java code for the approach
import java.io.*;
 
class GFG
{
 
  // Function to check whether the array
  // can be turned into palindrome after K
  // number of operations
  public static boolean check_possibility(int arr[],
                                          int K)
  {
 
    // Store the length of the array in
    // arr_length variable
    int arr_length = arr.length;
 
    // Initialize two pointers from left and
    // right ends of the array
    int i = 0;
    int j = arr_length - 1;
 
    // Keep iterating through the array from
    // two ends until the two pointers cross
    // each other to count the number
    // of the different array items.
    while (i < j) {
 
      // If the two elements are unequal,
      // decrease the value of K by one
      if (arr[i] != arr[j]) {
        K--;
      }
 
      // Move the left pointer towards the
      // right and right pointer towards the
      // left
      i++;
      j--;
    }
 
    // The unequal items are more than K or K
    // becomes less than zero, it is impossible
    // to make it a palindrome with D operations.
    if (K < 0) {
      return false;
    }
 
    // If K has a non-negative value, we make the
    // array a palindrome if it has an odd length
    // the remaining value of K is odd as we have
    // to choose two indices at a time to keep it
    // as a palindrome.
    else {
      if ((arr_length % 2) != 0 || (K % 2) == 0) {
        return true;
      }
      else {
        return false;
      }
    }
  }
  public static void main(String[] args)
  {
    int arr[] = { 1, 0, 1, 1, 0, 0 };
    int K = 1;
 
    // Function call
    if (check_possibility(arr, K) == true) {
      System.out.println("Yes");
    }
    else {
      System.out.println("No");
    }
  }
}
 
// This code is contributed by Rohit Pradhan
 
 

C#




// C# code for the approach
using System;
class GFG {
 
  // Function to check whether the array
  // can be turned into palindrome after K
  // number of operations
  static bool check_possibility(int[] arr, int K)
  {
 
    // Store the length of the array in
    // arr_length variable
    int arr_length = arr.Length;
 
    // Initialize two pointers from left and
    // right ends of the array
    int i = 0;
    int j = arr_length - 1;
 
    // Keep iterating through the array from
    // two ends until the two pointers cross
    // each other to count the number
    // of the different array items.
    while (i < j) {
 
      // If the two elements are unequal,
      // decrease the value of K by one
      if (arr[i] != arr[j]) {
        K--;
      }
 
      // Move the left pointer towards the
      // right and right pointer towards the
      // left
      i++;
      j--;
    }
 
    // The unequal items are more than K or K
    // becomes less than zero, it is impossible
    // to make it a palindrome with D operations.
    if (K < 0) {
      return false;
    }
 
    // If K has a non-negative value, we make the
    // array a palindrome if it has an odd length
    // the remaining value of K is odd as we have
    // to choose two indices at a time to keep it
    // as a palindrome.
    else {
      if ((arr_length % 2) != 0 || (K % 2) == 0) {
        return true;
      }
      else {
        return false;
      }
    }
  }
  public static int Main()
  {
    int[] arr = new int[] { 1, 0, 1, 1, 0, 0 };
    int K = 1;
 
    // Function call
    if (check_possibility(arr, K) == true) {
      Console.WriteLine("Yes");
    }
    else {
      Console.WriteLine("No");
    }
    return 0;
  }
}
 
// This code is contributed by Taranpreet
 
 

Python3




# Python code for the approach
 
def check_possibility(arr, K):
    
    # Store the length of the array in
    # arr_length variable
    arr_length = len(arr)
     
    # Initialize two pointers from left and right
    # ends of the array
    i = 0
    j = arr_length - 1
     
    # Keep iterating through the array from two
    # ends until the two pointers cross each
    # other to count the number of the different
    # array items.
    while(i < j):
       
        # If the two elements are unequal,
        # decrease the value of K by one
        if(arr[i] != arr[j]):
            K -= 1
 
        # Move the left pointer towards the right
        # and right pointer towards the left
        i += 1
        j -= 1
     
    # The unequal items are more than K or
    # K becomes less than zero, it is impossible
    # to make it a palindrome with K operations.
    if(K < 0):
        return False
     
    # If K has a non-negative value, we make the
    # array a palindrome if it has an odd length
    # the remaining value of K is odd as we have
    # to choose two indices at a time
    # to keep it as a palindrome
    else:
        if( (arr_length % 2)!= 0 or (K % 2)== 0):
            return True
     
        else:
            return False
 
# Driver code
if __name__ == '__main__':
    arr = [1, 0, 1, 1, 0, 0]
    K = 1
     
    if check_possibility(arr, K) == True :
        print("Yes")
    else:
        print("No")
 
 

Javascript




// JavaScript code for the approach
 
// Function to check whether the array
// can be turned into palindrome after K
// number of operations
function check_possibility(arr, K)
{
 
    // Store the length of the array in
    // arr_length variable
    var arr_length = arr.length;
 
    // Initialize two pointers from left and
    // right ends of the array
    var i = 0;
    var j = arr_length - 1;
 
    // Keep iterating through the array from
    // two ends until the two pointers cross
    // each other to count the number
    // of the different array items.
    while (i < j) {
 
        // If the two elements are unequal,
        // decrease the value of K by one
        if (arr[i] != arr[j]) {
            K--;
        }
 
        // Move the left pointer towards the
        // right and right pointer towards the
        // left
        i++;
        j--;
    }
 
    // The unequal items are more than K or K
    // becomes less than zero, it is impossible
    // to make it a palindrome with D operations.
    if (K < 0) {
        return false;
    }
 
    // If K has a non-negative value, we make the
    // array a palindrome if it has an odd length
    // the remaining value of K is odd as we have
    // to choose two indices at a time to keep it
    // as a palindrome.
    else {
        if ((arr_length % 2) != 0 || (K % 2) == 0) {
            return true;
        }
        else {
            return false;
        }
    }
}
 
// Driver code
var arr = [ 1, 0, 1, 1, 0, 0 ];
var K = 1;
 
// Function call
if (check_possibility(arr, K) == true) {
    console.log("Yes");
}
else {
    console.log("No");
}
 
// This code is contributed by phasing17
 
 
Output
Yes

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



Next Article
Check if given Array can be made a binary Array with K consecutive 1s

S

shinjanpatra
Improve
Article Tags :
  • Arrays
  • Bit Magic
  • DSA
  • Greedy
  • Bitwise-XOR
  • palindrome
Practice Tags :
  • Arrays
  • Bit Magic
  • Greedy
  • palindrome

Similar Reads

  • Check if Binary Array can be split into X Subarray with same bitwise XOR
    Given a binary array A[] and an integer X, the task is to check whether it is possible to divide A[] into exactly X non-empty and non-overlapping subarrays such that each Ai belongs to exactly one subarray and the bitwise XOR of each subarray is the same. Examples: Input: A[] = {0, 1, 1, 0, 0}, X =
    6 min read
  • Check if Binary Array can be made Palindrome by flipping two bits at a time
    Given a binary array A[] of size N, the task is to check whether the array can be converted into a palindrome by flipping two bits in each operation. Note: The operation can be performed any number of times. Examples: Input: A[] = {1, 0, 1, 0, 1, 1}Output: Yes?Explanation: We can perform the followi
    7 min read
  • Check if all elements of binary array can be made 1
    Given a binary array Arr and an integer K. If the value at index i is 1 you can change 0 to 1 with in the range of ( i - K ) to ( i + K ).The task is to determine whether all the elements of the array can be made 1 or not.Examples: Input: Arr = { 0, 1, 0, 1 }, K = 2 Output: 2 Input: Arr = { 1, 0, 0,
    7 min read
  • Check if given Array can be made a binary Array with K consecutive 1s
    Given an array A[] of size N and an integer K. Each element of the array is either 0, 1 or 2. The task is to check if the array can be converted into a binary array (elements will be either 0 or 1) by replacing every element equal to 2 with either 0 or 1, such that there are only K occurrences of 1,
    11 min read
  • Check if given Binary String can be made Palindrome using K flips
    Given a binary string str, the task is to determine if string str can be converted into a palindrome in K moves. In one move any one bit can be flipped i.e. 0 to 1 or 1 to 0. Examples: Input: str = "101100", K = 1Output: YESExplanation: Flip last bit of str from 0 to 1. Input: str = "0101101", K = 2
    5 min read
  • Check whether the number can be made palindromic after adding K
    Given two numbers N and K, the task is to check whether the given number N can be made a palindromic after adding K to it.Example: Input: N = 19, K = 3 Output: Yes Explanation: 19 + 3 = 22 and 22 is a palindrome.Input: N = 15, K = 3 Output: No Explanation: 15 + 3 = 18 and 18 is not a palindrome. App
    5 min read
  • Check if two Binary Strings can be made equal by doing bitwise XOR of adjacent
    Given binary strings S1 and S2 of length N, the task is to check if S2 can be made equal to S1 by performing the following operations on S2: The first operation is Si = Si ? Si+1. ( ? is the XOR operation)The second operation is Si+1 = Si+1 ? Si. Examples: Input: S1 = "00100", S2 = "00011" Output: Y
    6 min read
  • Check if elements of a Binary Matrix can be made alternating
    Given a 2D array grid[][] of size N * M, consisting of the characters "1", "0", and "*", where "*" denotes an empty space and can be replaced by either a "1" or a "0". The task is to fill the grid such that "0" and "1" occur alternatively and no two consecutive characters occur together, i.e. (10101
    15+ min read
  • Check if Array can be rearranged such that arr[i] XOR arr[i+2] is 0
    Given an array arr[] of size N, the task is to check if the array elements can be rearranged in a way such that the bitwise XOR of ith and (i+2)th element is always 0 for any value of i (0 ≤ i < N-2) Examples: Input: arr[] = {1, 1, 2, 2}, N = 4Output: YESExplanation: Rearrange the array like {1,
    8 min read
  • Minimize XOR of pairs to make the Array Palindrome
    Given an array arr[] of size N consisting only of 0s and 1s, the task is to find the minimum number of operations required to make the array a palindrome where in each operation you can choose any two elements at positions i and j and replace both arr[i] and arr[j] with arr[i]^arr[j] (where ^ repres
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences