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:
Split an array into subarrays with maximum Bitwise XOR of their respective Bitwise OR values
Next article icon

Check if Binary Array can be split into X Subarray with same bitwise XOR

Last Updated : 10 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 = 3 
Output: Yes
?Explanation: One of the possible ways of dividing A is {0}, {1, 1} & {0, 0}. Here XOR of each subarray is 0.

Input: A[] = {1, 1, 1}, X = 2 
?Output: No

Approach: The problem can be solved based on the following observation: 

The bitwise XOR of any binary array is either 0 or 1. Therefore if an answer exists then it is either X non-overlapping subarrays having XOR equal to 1 or X non - overlapping subarrays having XOR equal to 0. We can iterate over the binary array and check whether we can divide the array into X non-overlapping subarrays having XOR equal to 0 or X non-overlapping substrings having XOR equal to 1.

Follow the steps mentioned below to implement the above idea:

  • First set xor = 0, count0 = 0 and count1 = 0 . 
  • Iterate a loop to count the number of times the xor of the prefix element of the array is 0. Let's say the count is count0.
  • After that check count0 ? X and xor != 1, if it is true then return "Yes".
    • If it is not true set the xor = 0.
    • Iterate another loop to count the number of times the xor of the prefix element of the array is 1 and reset xor = 0. Let's say the count is count1.
    • After that check count1 ? X and (count1 - X) % 2 == 0, if it is true then return "Yes".
    • Otherwise, return "No".

Below is the implementation of the above approach.

C++
// C++ code to implement the approach #include <iostream> #include <vector> using namespace std;  // Function to find check whether // array can be divided into exactly // X non-empty subarrays string check(vector<int> &arr, int n, int x) {     int xor_ = 0;     int count0 = 0, count1 = 0;          for (int i = 0; i < n; i++) {         xor_ ^= arr[i];         if (xor_ == 0)             count0++;     }     if (count0 >= x && xor_ != 1) {         return "Yes";     }     xor_ = 0;     for (int i = 0; i < n; i++) {         xor_ ^= arr[i];         if (xor_ == 1) {             count1++;             xor_ = 0;         }     }     if (count1 >= x && (count1 - x) % 2 == 0) {         return "Yes";     }     return "No"; }  // Driver Code int main() {     vector<int> A = { 0, 1, 1, 0, 0 };     int N = A.size();     int X = 3;          // Function Call     cout << check(A, N, X) << endl;     return 0; }  // This code is contributed Tapesh(tapeshdua420) 
Java
// Java code to implement the approach  import java.io.*; import java.util.*;  public class GFG {      // Function to find check whether     // array can be divided into exactly     // X non-empty subarrays     public static String check(int arr[], int n, int x)     {         int xor = 0;         int count0 = 0, count1 = 0;          for (int i = 0; i < n; i++) {             xor ^= arr[i];             if (xor == 0)                 count0++;         }         if (count0 >= x && xor != 1) {             return "Yes";         }         xor = 0;         for (int i = 0; i < n; i++) {             xor ^= arr[i];             if (xor == 1) {                 count1++;                 xor = 0;             }         }         if (count1 >= x && (count1 - x) % 2 == 0) {             return "Yes";         }         return "No";     }      // Driver Code     public static void main(String[] args)     {         int[] A = { 0, 1, 1, 0, 0 };         int N = A.length;         int X = 3;          // Function Call         System.out.println(check(A, N, X));     } } 
Python3
# Python code to implement the approach  # Function to find check whether # array can be divided into exactly # X non-empty subarrays def check(arr, n, x):     xor = 0     count0 = 0     count1 = 0          for i in range(n):         xor ^= arr[i]         if xor == 0:             count0 += 1                  if count0 >= x and xor != 1:         return "Yes"          xor = 0     for i in range(n):         xor ^= arr[i]         if xor == 1:             count1 += 1             xor = 0                  if count1 >= x and (count1 - x) % 2 == 0:         return "Yes"      return "No"  # Driver Code if __name__ == '__main__':     A = [0, 1, 1, 0, 0]       N = len(A)       X = 3           # Function Call     print(check(A, N, X))      # This code is contributed Tapesh(tapeshdua420) 
C#
// C# code to implement the approach using System;  class Program {     // Driver Code     static void Main(string[] args)     {         int[] A = { 0, 1, 1, 0, 0 };         int N = A.Length;         int X = 3;          // Function Call         Console.WriteLine(check(A, N, X));     }      // Function to find check whether     // array can be divided into exactly     // X non-empty subarrays     public static string check(int[] arr, int n, int x)     {         int xor = 0;         int count0 = 0, count1 = 0;          for (int i = 0; i < n; i++) {             xor ^= arr[i];             if (xor == 0)                 count0++;         }         if (count0 >= x && xor != 1) {             return "Yes";         }         xor = 0;         for (int i = 0; i < n; i++) {             xor ^= arr[i];             if (xor == 1) {                 count1++;                 xor = 0;             }         }          if (count1 >= x && ((count1 - x) % 2 == 0)) {             return "Yes";         }         return "No";     } }  // This code is contributed by Tapesh(tapeshdua420) 
JavaScript
  // JavaScript code to implement the approach    // Function to find check whether   // array can be divided into exactly   // X non-empty subarrays   function check(arr, n, x) {       let xor = 0       let count0 = 0, count1 = 0        for (let i = 0; i < n; i++) {           xor ^= arr[i]           if (xor == 0)               count0++       }       if (count0 >= x && xor != 1) {           return "Yes"       }       xor = 0       for (let i = 0; i < n; i++) {           xor ^= arr[i]           if (xor == 1) {               count1++               xor = 0           }       }       if (count1 >= x && (count1 - x) % 2 == 0) {           return "Yes"       }       return "No"   }    // Driver Code   var A = [ 0, 1, 1, 0, 0 ]   var N = A.length   var X = 3    // Function Call   console.log(check(A, N, X))    // This code is contributed Tapesh(tapeshdua420). 

Output
Yes

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


Next Article
Split an array into subarrays with maximum Bitwise XOR of their respective Bitwise OR values
author
aarohirai2616
Improve
Article Tags :
  • Bit Magic
  • Competitive Programming
  • DSA
  • Arrays
  • subarray
Practice Tags :
  • Arrays
  • Bit Magic

Similar Reads

  • Check if Binary Array can be made palindrome after K bitwise XOR with 1
    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. Exa
    9 min read
  • Check if an array can be split into K non-overlapping subarrays whose Bitwise AND values are equal
    Given an array arr[] of size N and a positive integer K, the task is to check if the array can be split into K non-overlapping and non-empty subarrays such that Bitwise AND of all the subarrays are equal. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: arr[] = { 3, 2,
    11 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
  • Count ways to split array into three non-empty subarrays having equal Bitwise XOR values
    Given an array arr[] consisting of N non-negative integers, the task is to count the number of ways to split the array into three different non-empty subarrays such that Bitwise XOR of each subarray is equal. Examples: Input: arr[] = {7, 0, 5, 2, 7} Output: 2Explanation: All possible ways are:{{7},
    9 min read
  • Split an array into subarrays with maximum Bitwise XOR of their respective Bitwise OR values
    Given an array arr[] consisting of N integers, the task is to find the maximum Bitwise XOR of Bitwise OR of every subarray after splitting the array into subarrays(possible zero subarrays). Examples: Input: arr[] = {1, 5, 7}, N = 3Output: 7Explanation:The given array can be expressed as the 1 subarr
    9 min read
  • Check if MEX of an Array can be changed with atmost one Subarray replacement
    Given an array arr[] of size N, the task is to check if can you change the MEX of the array to MEX + 1 by replacing at most one subarray with any positive integer. Follow 0-based indexing. Note: The MEX of the array is the smallest non-negative number that is not present in the array. Examples: Inpu
    11 min read
  • Split Array into maximum Subsets with same bitwise AND
    Given an array arr[] of size N, the task is to find the maximum number of subsets the array can be split such that the bitwise AND of the subsets is the same. Examples: Input: N = 4, arr[] = {1, 5, 2, 8}Output: 2Explanation:1st subset -> {1, 8}; bitwise AND = 0 2nd subset -> {2, 5}; bitwise AN
    10 min read
  • Count pairs in Array such that their bitwise XOR has Kth right bit set
    Given an array arr[] of size N and an integer K, the task is to find the number of pairs in the array such that the Kth bit from the right of their bitwise XOR is set. Examples: Input: arr[] = {3, 13, 2, 9}, N = 4, K = 3Output: 4Explanation: The pairs that have the kth bit set in bitwise xor value a
    11 min read
  • Check in binary array the number represented by a subarray is odd or even
    Given an array such that all its terms is either 0 or 1.You need to tell the number represented by a subarray a[l..r] is odd or even Examples : Input : arr = {1, 1, 0, 1} l = 1, r = 3 Output : odd number represented by arr[l...r] is 101 which 5 in decimal form which is odd Input : arr = {1, 1, 1, 1}
    4 min read
  • Minimize insertions in Array to divide it in pairs with Bitwise XOR as X
    Given an array arr of length N of distinct numbers and an integer X, the task is to find the minimum number of elements that should be added in the array such that the array elements can be grouped in pairs where the bitwise XOR of each pair is equal to X. Examples: Input: N = 3, arr[] = {1, 2, 3},
    7 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