Find Maximum XOR value of a sub-array of size k in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[] consisting of n elements and an integer k. Our task is to find the Maximum XOR value of a sub-array of size k.

Let’s take an example to understand the problem,

Input

arr[] = {3, 1, 6, 2 ,7, 9} k = 3

Output

12

Explanation

All subarray and the xor of all element of size k,

{3, 1, 6} = 4
{1, 6, 2} = 5
{6, 2, 7} = 3
{2, 7, 9} = 12

Solution Approach

A simple solution to the problem is by using two loops. One to iterate over the array and other to find the XOR of all elements of the subarray. And then return the maximum of all.

This solution is ok but a better approach to solve the problem can be made. We need to find the sum by starting from the subarray of size k starting from

index 0. And then iterating the array and adding a new element to XOR and deleting the first one. Deletion is possible by using the formula x^a^x = a.

So, for each interaction we will first perform, XOR ^ arr[i - k], which will give the value of the subarray from last index + 1 to the current index - 1.

Then we will perform XOR of subarray with arr[i], to get the current XOR. We will find and return the maximum value out of all XOR’s.

Program to illustrate the working of our solution,

Example

 Live Demo

#include<iostream>
using namespace std;
int findMaxSubArrayXOR(int arr[] , int n , int k) {
   int currentXORVal = 0 ;
   for (int i = 0 ; i < k ; i++)
   currentXORVal = currentXORVal ^ arr[i];
   int maxXor = currentXORVal;
   for (int i = k ; i < n; i++) {
      currentXORVal = currentXORVal ^ arr[i-k];
      currentXORVal = currentXORVal ^ arr[i];
      maxXor = max(maxXor, currentXORVal);
   }
   return maxXor;
}
int main() {
   int arr[] = {3, 1, 6, 2, 7, 9};
   int n = sizeof(arr)/sizeof(arr[0]);
   int k = 3;
   cout<<"The maximum XOR of subarray of size "<<k<<" is "<<findMaxSubArrayXOR(arr, n, k);
   return 0;
}

Output

The maximum XOR of subarray of size 3 is 12
raja
Published on 12-Mar-2021 06:37:25
Advertisements