Length of the longest subarray whose Bitwise XOR is K

17 May, 2021
Given an array arr[] of size N and an integer K, the task is to find the length of the longest subarray having Bitwise XOR of all its elements equal to K.
Examples:
Input: arr[] = { 1, 2, 4, 7, 2 }, K = 1Output: 3Explanation: Subarray having Bitwise XOR equal to K(= 1) are { { 1 }, { 2, 4, 7 }, { 1 } }.Therefore, the length of longest subarray having bitwise XOR equal to K(= 1) is 3
Input: arr[] = { 2, 5, 6, 1, 0, 3, 5, 6 }, K = 4Output: 6Explanation:Subarray having Bitwise XOR equal to K(= 4) are { { 6, 1, 0, 3 }, { 5, 6, 1, 0, 3, 5 } }.Therefore, the length of longest subarray having bitwise XOR equal to K(= 4) is 6.
Approach: The problem can be solved using Hashing and Prefix Sum technique. Following are the observation:
a1 ^ a2 ^ a3 ^ ..... ^ an = K
=> a2 ^ a3 ^ ..... ^ an ^ K = a1
Follow the steps below to solve the problem:
Initialize a variable, say prefixXOR, to store the Bitwise XOR of all elements up to the ith index of the given array.
Initialize a Map, say mp, to store the indices of the computed prefix XORs of the array.
Initialize a variable, say maxLen, to store the length of the longest subarray whose Bitwise XOR is equal to K.
Traverse the array arr[] using variable i. For every ith index, update prefixXOR = prefixXOR ^ arr[i] and check if (prefixXOR ^ K) is present in the Map or not. If found to be true, then update maxLen = max(maxLen, i – mp[prefixXOR ^ K]).
If prefixXOR is not present in the Map, then insert prefixXOR into the Map.
Finally, print the value of maxLen.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the length of the longest// subarray whose bitwise XOR is equal to Kint LongestLenXORK(int arr[], int N, int K){         // Stores prefix XOR    // of the array    int prefixXOR = 0;     // Stores length of longest subarray    // having bitwise XOR equal to K    int maxLen = 0;     // Stores index of prefix    // XOR of the array    map<int, int> mp;              // Insert 0 into the map    mp[0] = -1;     // Traverse the array    for (int i = 0; i < N; i++) {         // Update prefixXOR        prefixXOR ^= arr[i];         // If (prefixXOR ^ K) present        // in the map        if (mp.count(prefixXOR ^ K)) {             // Update maxLen            maxLen = max(maxLen,               (i - mp[prefixXOR ^ K]));        }                 // If prefixXOR not present        // in the Map        if (!mp.count(prefixXOR)) {             // Insert prefixXOR            // into the map            mp[prefixXOR] = i;        }    }         return maxLen;} // Driver Codeint main(){    int arr[] = { 1, 2, 4, 7, 2 };    int N = sizeof(arr) / sizeof(arr[0]);    int K = 1;    cout<< LongestLenXORK(arr, N, K);     return 0;}
// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to find the length of the longest// subarray whose bitwise XOR is equal to Kstatic int LongestLenXORK(int arr[],                          int N, int K){         // Stores prefix XOR    // of the array    int prefixXOR = 0;     // Stores length of longest subarray    // having bitwise XOR equal to K    int maxLen = 0;     // Stores index of prefix    // XOR of the array    HashMap<Integer,            Integer> mp = new HashMap<Integer,                                      Integer>();                                           // Insert 0 into the map    mp.put(0, -1);     // Traverse the array    for(int i = 0; i < N; i++)    {                 // Update prefixXOR        prefixXOR ^= arr[i];         // If (prefixXOR ^ K) present        // in the map        if (mp.containsKey(prefixXOR ^ K))        {                         // Update maxLen            maxLen = Math.max(maxLen,               (i - mp.get(prefixXOR ^ K)));        }                 // If prefixXOR not present        // in the Map        if (!mp.containsKey(prefixXOR))        {                         // Insert prefixXOR            // into the map            mp.put(prefixXOR, i);        }    }    return maxLen;} // Driver Codepublic static void main(String[] args){    int arr[] = { 1, 2, 4, 7, 2 };    int N = arr.length;    int K = 1;         System.out.print(LongestLenXORK(arr, N, K));}} // This code is contributed by Amit Katiyar
# Python3 program to implement# the above approach # Function to find the length of the longest# subarray whose bitwise XOR is equal to Kdef LongestLenXORK(arr, N, K):         # Stores prefix XOR    # of the array    prefixXOR = 0     # Stores length of longest subarray    # having bitwise XOR equal to K    maxLen = 0     # Stores index of prefix    # XOR of the array    mp = {}     # Insert 0 into the map    mp[0] = -1     # Traverse the array    for i in range(N):                 # Update prefixXOR        prefixXOR ^= arr[i]         # If (prefixXOR ^ K) present        # in the map        if (prefixXOR ^ K) in mp:                         # Update maxLen            maxLen = max(maxLen,                        (i - mp[prefixXOR ^ K]))         # If prefixXOR not present        # in the Map        else:                         # Insert prefixXOR            # into the map            mp[prefixXOR] = i           return maxLen # Driver Codeif __name__ == "__main__" :     arr = [ 1, 2, 4, 7, 2 ]    N = len(arr)    K = 1         print(LongestLenXORK(arr, N, K)) # This code is contributed by AnkThon
// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find the length of the longest// subarray whose bitwise XOR is equal to Kstatic int longestLenXORK(int []arr,                          int N, int K){         // Stores prefix XOR    // of the array    int prefixXOR = 0;     // Stores length of longest subarray    // having bitwise XOR equal to K    int maxLen = 0;     // Stores index of prefix    // XOR of the array    Dictionary<int,            int> mp = new Dictionary<int,                                      int>();                                           // Insert 0 into the map    mp.Add(0, -1);     // Traverse the array    for(int i = 0; i < N; i++)    {                 // Update prefixXOR        prefixXOR ^= arr[i];         // If (prefixXOR ^ K) present        // in the map        if (mp.ContainsKey(prefixXOR ^ K))        {                         // Update maxLen            maxLen = Math.Max(maxLen,               (i - mp[prefixXOR ^ K]));        }                 // If prefixXOR not present        // in the Map        if (!mp.ContainsKey(prefixXOR))        {                         // Insert prefixXOR            // into the map            mp.Add(prefixXOR, i);        }    }    return maxLen;} // Driver Codepublic static void Main(String[] args){    int []arr = {1, 2, 4, 7, 2};    int N = arr.Length;    int K = 1;         Console.Write(longestLenXORK(arr, N, K));}} // This code is contributed by shikhasingrajput
<script> // JavaScript program to implement// the above approach // Function to find the length of the longest// subarray whose bitwise XOR is equal to Kfunction LongestLenXORK(arr, N, K){         // Stores prefix XOR    // of the array    var prefixXOR = 0;     // Stores length of longest subarray    // having bitwise XOR equal to K    var maxLen = 0;     // Stores index of prefix    // XOR of the array    var mp = new Map();              // Insert 0 into the map    mp.set(0, -1);     // Traverse the array    for (var i = 0; i < N; i++) {         // Update prefixXOR        prefixXOR ^= arr[i];         // If (prefixXOR ^ K) present        // in the map        if (mp.has(prefixXOR ^ K)) {             // Update maxLen            maxLen = Math.max(maxLen,               (i - mp.get(prefixXOR ^ K)));        }                 // If prefixXOR not present        // in the Map        if (!mp.has(prefixXOR)) {             // Insert prefixXOR            // into the map            mp.set(prefixXOR, i);        }    }         return maxLen;} // Driver Codevar arr = [1, 2, 4, 7, 2];var N =  arr.length;var K = 1;document.write( LongestLenXORK(arr, N, K)); </script>
Output:
3
Time Complexity: O(N)Auxiliary Space: O(N)
amit143katiyar
ankthon
shikhasingrajput
rrrtnx
Bitwise-XOR
cpp-map
Hash
prefix
subarray
Arrays
Bit Magic
Hash
Mathematical
Arrays
Hash
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
How to swap two numbers without using a temporary variable?