Skip to content
Related Articles

Related Articles

Find a K-length subarray having Bitwise XOR equal to that of remaining array elements
  • Difficulty Level : Easy
  • Last Updated : 25 Jan, 2021

Given an array arr[] of size N, the task is to check if any subarray of size K exists in the array or not, whose Bitwise XOR is equal to the Bitwise XOR of the remaining array elements. If found to be true, then print “YES”. Otherwise, print “NO”.

Examples:

Input: arr[] = { 2, 3, 3, 5, 7, 7, 3, 4 }, K = 5 
Output: YES 
Explanation: 
Bitwise XOR of the subarray { 3, 3, 5, 7, 7 } is equal to 5 
Bitwise XOR of { 2, 3, 4 } is equal to 5. 
Therefore, the required output is YES.

Input: arr[] = { 2, 3, 4, 5, 6, 7, 4 }, K = 2 
Output: NO

Naive Approach: The simplest approach to solve this problem is to generate all subarrays of size K. For each subarray, check if the bitwise XOR of the subarray is equal to bitwise XOR of remaining elements or not. If found to be true, then print “YES”. Otherwise, print “NO”



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

Efficient Approach: The above approach can be optimized using Sliding Window Technique Following are the observations:

If X ^ Y = Z, then X ^ Z = Y 
SubarrayXOR = arr[i] ^ arr[i + 1] ^ … ^ arr[j] 
totalXOR = arr[0] ^ arr[1] ^ arr[2] ….. ^ arr[N – 1] 
Bitwise XOR of the remaining array elements = totalXOR ^ SubarrayXOR 
 

  • Calculate the Bitwise XOR of all array elements, say totalXOR.
  • Calculate the Bitwise XOR of first K elements of the array, say SubarrayXOR.
  • Use sliding window technique, traverse each subarray of size K and check if Bitwise XOR of the subarray is equal to the Bitwise XOR of the remaining array elements or not. If found to be true, then print “YES”.
  • Otherwise, print “NO”.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Utility function to check if subarray
// of size K exits whose XOR of elements
// equal to XOR ofremaning array elements
bool isSubarrayExistUtil(int arr[], int K, int N)
{
 
    int totalXOR = 0;
    int SubarrayXOR = 0;
 
    // Find XOR of whole array
    for (int i = 0; i < N; i++)
        totalXOR ^= arr[i];
 
    // Find XOR of first K elements
    for (int i = 0; i < K; i++)
        SubarrayXOR ^= arr[i];
    if (SubarrayXOR == (totalXOR ^ SubarrayXOR))
        return true;
 
    for (int i = K; i < N; i++) {
 
        // Adding XOR of next element
        SubarrayXOR ^= arr[i];
 
        // Removing XOR of previous element
        SubarrayXOR ^= arr[i - 1];
 
        // Check if XOR of current subarray matches
        // with the XOR of remaining elements or not
        if (SubarrayXOR == (totalXOR ^ SubarrayXOR))
            return true;
    }
    return false;
}
 
// Function to check if subarray of size
// K exits whose XOR of elements equal
// to XOR ofremaning array elements
void isSubarrayExist(int arr[], int K, int N)
{
    if (isSubarrayExistUtil(arr, K, N))
        cout << "YES\n";
    else
        cout << "NO\n";
}
 
// Driver Code
int32_t main()
{
    // Given array
    int arr[] = { 2, 3, 3, 5, 7, 7, 3, 4 };
 
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Given K
    int K = 5;
 
    // Function Call
    isSubarrayExist(arr, K, N);
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
 
// Utility function to check if subarray
// of size K exits whose XOR of elements
// equal to XOR ofremaning array elements
static boolean isSubarrayExistUtil(int arr[],
                                   int K, int N)
{
    int totalXOR = 0;
    int SubarrayXOR = 0;
 
    // Find XOR of whole array
    for(int i = 0; i < N; i++)
        totalXOR ^= arr[i];
 
    // Find XOR of first K elements
    for(int i = 0; i < K; i++)
        SubarrayXOR ^= arr[i];
    if (SubarrayXOR == (totalXOR ^ SubarrayXOR))
        return true;
 
    for(int i = K; i < N; i++)
    {
         
        // Adding XOR of next element
        SubarrayXOR ^= arr[i];
 
        // Removing XOR of previous element
        SubarrayXOR ^= arr[i - 1];
 
        // Check if XOR of current subarray matches
        // with the XOR of remaining elements or not
        if (SubarrayXOR == (totalXOR ^ SubarrayXOR))
            return true;
    }
    return false;
}
 
// Function to check if subarray of size
// K exits whose XOR of elements equal
// to XOR ofremaning array elements
static void isSubarrayExist(int arr[],
                            int K, int N)
{
    if (isSubarrayExistUtil(arr, K, N))
        System.out.print("YES\n");
    else
        System.out.print("NO\n");
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array
    int arr[] = { 2, 3, 3, 5, 7, 7, 3, 4 };
 
    // Size of the array
    int N = arr.length;
 
    // Given K
    int K = 5;
 
    // Function Call
    isSubarrayExist(arr, K, N);
}
}
 
// This code is contributed by 29AjayKumar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above approach
 
# Utility function to check if subarray
# of size K exits whose XOR of elements
# equal to XOR ofremaning array elements
def isSubarrayExistUtil(arr, K, N):
    totalXOR = 0
    SubarrayXOR = 0
 
    # Find XOR of whole array
    for i in range(N):
        totalXOR ^= arr[i]
 
    # Find XOR of first K elements
    for i in range(K):
        SubarrayXOR ^= arr[i]
    if (SubarrayXOR == (totalXOR ^ SubarrayXOR)):
        return True
 
    for i in range(K, N):
 
        # Adding XOR of next element
        SubarrayXOR ^= arr[i]
 
        # Removing XOR of previous element
        SubarrayXOR ^= arr[i - 1]
 
        # Check if XOR of current subarray matches
        # with the XOR of remaining elements or not
        if (SubarrayXOR == (totalXOR ^ SubarrayXOR)):
            return True
    return False
 
# Function to check if subarray of size
# K exits whose XOR of elements equal
# to XOR ofremaning array elements
def isSubarrayExist(arr, K, N):
    if (isSubarrayExistUtil(arr, K, N)):
        print("YES")
    else:
        print("NO")
 
# Driver Code
if __name__ == '__main__':
     
    # Given array
    arr = [2, 3, 3, 5, 7, 7, 3, 4]
 
    # Size of the array
    N = len(arr)
 
    # Given K
    K = 5
 
    # Function Call
    isSubarrayExist(arr, K, N)
 
    # This code is contributed by mohit kumar 29

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
class GFG
{
 
// Utility function to check if subarray
// of size K exits whose XOR of elements
// equal to XOR ofremaning array elements
static bool isSubarrayExistUtil(int []arr,
                                   int K, int N)
{
    int totalXOR = 0;
    int SubarrayXOR = 0;
 
    // Find XOR of whole array
    for(int i = 0; i < N; i++)
        totalXOR ^= arr[i];
 
    // Find XOR of first K elements
    for(int i = 0; i < K; i++)
        SubarrayXOR ^= arr[i];
    if (SubarrayXOR == (totalXOR ^ SubarrayXOR))
        return true;
    for(int i = K; i < N; i++)
    {
         
        // Adding XOR of next element
        SubarrayXOR ^= arr[i];
 
        // Removing XOR of previous element
        SubarrayXOR ^= arr[i - 1];
 
        // Check if XOR of current subarray matches
        // with the XOR of remaining elements or not
        if (SubarrayXOR == (totalXOR ^ SubarrayXOR))
            return true;
    }
    return false;
}
 
// Function to check if subarray of size
// K exits whose XOR of elements equal
// to XOR ofremaning array elements
static void isSubarrayExist(int []arr,
                            int K, int N)
{
    if (isSubarrayExistUtil(arr, K, N))
        Console.Write("YES\n");
    else
        Console.Write("NO\n");
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given array
    int []arr = { 2, 3, 3, 5, 7, 7, 3, 4 };
 
    // Size of the array
    int N = arr.Length;
 
    // Given K
    int K = 5;
 
    // Function Call
    isSubarrayExist(arr, K, N);
}
}
 
// This code is contributed by 29AjayKumar

chevron_right


Output: 

YES

 

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :