Length of the longest subarray whose Bitwise XOR is K
Last Updated :
26 Sep, 2023
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 = 1
Output: 3
Explanation:
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 = 4
Output: 6
Explanation:
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.
Naive Approach
The idea is to generate all subarrays and find that subarray whose bitwise XOR of all elements is equal to K and has a maximum length
Steps to Implement:
- Initialize a variable "ans" with 0 because if no such subarray exists then it will be the answer
- Run two for loops from 0 to N-1 to generate all subarray
- For each subarray find the XOR of all elements and its length
- If any XOR value got equal to K then update "ans" as the maximum of "ans" and the length of that subarray
- In the last print/return value in ans
Code-
C++
// 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 K
int LongestLenXORK(int arr[], int N, int K)
{
//To store final answer
int ans=0;
//Find all subarray
for(int i=0;i<N;i++){
//To store length of subarray
int length=0;
//To store XOR of all elements of subarray
int temp=0;
for(int j=i;j<N;j++){
temp=temp^arr[j];
length++;
//When XOR of all elements of subarray equal to K
if(temp==K){
//Update ans
ans=max(ans,length);
}
}
}
return ans;
}
// Driver Code
int 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
// Java program to implement
// the above approach
import java.util.*;
class GFG {
// Function to find the length of the longest
// subarray whose bitwise XOR is equal to K
static int LongestLenXORK(int[] arr, int N, int K)
{
// To store the final answer
int ans = 0;
// Find all subarrays
for (int i = 0; i < N; i++) {
// To store the length of the subarray
int length = 0;
// To store XOR of all elements of the subarray
int temp = 0;
for (int j = i; j < N; j++) {
temp = temp ^ arr[j];
length++;
// When XOR of all elements of subarray is
// equal to K
if (temp == K) {
// Update ans
ans = Math.max(ans, length);
}
}
}
return ans;
}
// Driver Code
public static void main(String[] args)
{
int[] arr = { 1, 2, 4, 7, 2 };
int N = arr.length;
int K = 1;
System.out.println(LongestLenXORK(arr, N, K));
}
}
Python3
# Python program to implement the above approach
# Function to find the length of the longest
# subarray whose bitwise XOR is equal to K
def LongestLenXORK(arr, N, K):
# To store final answer
ans = 0
# Find all subarray
for i in range(N):
# To store length of subarray
length = 0
# To store XOR of all elements of subarray
temp = 0
for j in range(i, N):
temp ^= arr[j]
length += 1
# When XOR of all elements of subarray equal to K
if temp == K:
# Update ans
ans = max(ans, length)
return ans
# Driver Code
if __name__ == '__main__':
arr = [1, 2, 4, 7, 2]
N = len(arr)
K = 1
print(LongestLenXORK(arr, N, K))
C#
using System;
class GFG
{
// Function to find the length of the longest
// subarray whose bitwise XOR is equal to K
static int LongestLenXORK(int[] arr, int N, int K)
{
// To store the final answer
int ans = 0;
// Find all subarrays
for (int i = 0; i < N; i++)
{
// To store the length of the subarray
int length = 0;
// To store the XOR of all elements of the subarray
int temp = 0;
for (int j = i; j < N; j++)
{
temp ^= arr[j];
length++;
// When XOR of all elements of the subarray is equal to K
if (temp == K)
{
// Update ans
ans = Math.Max(ans, length);
}
}
}
return ans;
}
// Driver Code
static void Main(string[] args)
{
int[] arr = { 1, 2, 4, 7, 2 };
int N = arr.Length;
int K = 1;
Console.WriteLine(LongestLenXORK(arr, N, K));
}
}
// This code is contributed by Dwaipayan Bandyopadhyay
JavaScript
// Javascript program to implement
// the above approach
// Function to find the length of the longest
// subarray whose bitwise XOR is equal to K
function LongestLenXORK(arr, N, K) {
//To store final answer
let ans = 0;
//Find all subarray
for (let i = 0; i < N; i++) {
let length = 0;
//To store XOR of all elements of subarray
let temp = 0;
for (let j = i; j < N; j++) {
temp ^= arr[j];
length += 1;
//When XOR of all elements of subarray equal to K
if (temp === K) {
//Update ans
ans = Math.max(ans, length);
}
}
}
return ans;
}
// Driver Code
const arr = [1, 2, 4, 7, 2];
const N = arr.length;
const K = 1;
console.log(LongestLenXORK(arr, N, K));
Output-
3
Time Complexity: O(N2), because of two nested loops from 0 to N-1
Auxiliary Space: O(1), because no extra space has been used
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++
// 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 K
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
unordered_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 Code
int 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
// Java program to implement
// the above approach
import java.util.*;
class GFG{
// Function to find the length of the longest
// subarray whose bitwise XOR is equal to K
static 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 Code
public 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
# Python3 program to implement
# the above approach
# Function to find the length of the longest
# subarray whose bitwise XOR is equal to K
def 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 Code
if __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#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to find the length of the longest
// subarray whose bitwise XOR is equal to K
static 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 Code
public 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
JavaScript
<script>
// JavaScript program to implement
// the above approach
// Function to find the length of the longest
// subarray whose bitwise XOR is equal to K
function 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 Code
var arr = [1, 2, 4, 7, 2];
var N = arr.length;
var K = 1;
document.write( LongestLenXORK(arr, N, K));
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read