Maximum XOR subarray of K distinct integer
Last Updated :
27 Apr, 2023
Given an array A consisting of N positive integers, the task is to calculate the maximum XOR of the subarray of size K consisting of all distinct integers. If such subarray is not present then Print "-1".
Examples:
Input: N = 10, A[] = [2, 3, 4, 2, 4, 5, 7, 4, 3, 9], K = 4
Output: 9
Explanation : All Subarrays of size K with all distinct integers are [2, 4, 5, 7], [5, 7, 4, 3], [7, 4, 3, 9] and there XOR are 6, 5, 9 respectively. So Maximum XOR of subarray is 9.
Input: N = 5, A[] = [2, 3, 2, 3, 2], K = 3
Output: -1
Explanation: Since there of no subarray of size K with all integers distinct
Naive Solution: The basic way to solve the problem is as follows:
A Simple Solution is to generate all subarrays of size K, check if all the integers in that subarray are distinct, compute their XORs, and finally return the maximum of all XORs, if no subarray of size K with all distinct is found return -1.
Below is the implementation of the above approach:
C++
// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
// Function performing Calculation
int maximumXorsubarray(int N, vector<int>& A, int K)
{
// Variable for storing maximum XOR
// of the subarray of size K
int mx = -1;
// Generating all subarray of size K
for (int i = 0; i < N - K + 1; i++) {
// Set is used for storing the
// element of subarray and
// checking distinct condition
unordered_set<int> st;
for (int j = i; j < i + K; j++) {
st.insert(A[j]);
}
// If subarray is of size K with
// all distinct
if (st.size() == K) {
// Calculating xor of the
// subarray of size K
int xorr = 0;
for (auto it : st) {
xorr = (xorr ^ it);
}
// update mx
mx = max(mx, xorr);
}
}
// Returning the Maximum XOR of subarray
// of size K with all distinct
return mx;
}
// Driver function
int main()
{
// Size of given subarray
int N = 10;
// Given array A
vector<int> A = { 2, 3, 4, 2, 4, 5, 7, 4, 3, 9 };
// Size of subarray needed
int K = 4;
// Function Call
cout << "Maximum XOR of subarray of size K with all "
"distincts are : "
<< maximumXorsubarray(N, A, K);
return 0;
}
Java
// Java code for the above approach:
import java.util.*;
class GFG {
// Function performing Calculation
static int maximumXorsubarray(int N,int A[], int K)
{
// Variable for storing maximum XOR
// of the subarray of size K
int mx = -1;
// Generating all subarray of size K
for (int i = 0; i < N - K + 1; i++) {
// Set is used for storing the
// element of subarray and
// checking distinct condition
Set<Integer> st = new HashSet<>();
for (int j = i; j < i + K; j++) {
st.add(A[j]);
}
// If subarray is of size K with
// all distinct
if (st.size() == K) {
// Calculating xor of the
// subarray of size K
int xorr = 0;
for (Integer it : st) {
xorr = (xorr ^ it);
}
// update mx
mx = Math.max(mx, xorr);
}
}
// Returning the Maximum XOR of subarray
// of size K with all distinct
return mx;
}
// Driver function
public static void main (String[] args) {
// Size of given subarray
int N = 10;
// Given array A
int A[] = { 2, 3, 4, 2, 4, 5, 7, 4, 3, 9 };
// Size of subarray needed
int K = 4;
// Function Call
System.out.println( "Maximum XOR of subarray of size K with all distincts are : " + maximumXorsubarray(N, A, K));
}
}
Python3
# Python3 code for the above approach
from typing import List
# Function performing Calculation
def maximumXorsubarray(N: int, A: List[int], K: int) -> int:
# Variable for storing maximum XOR
# of the subarray of size K
mx = -1
# Generating all subarray of size K
for i in range(N - K + 1):
# Set is used for storing the
# element of subarray and
# checking distinct condition
st = set()
for j in range(i, i + K):
st.add(A[j])
# If subarray is of size K with
# all distinct
if len(st) == K:
# Calculating xor of the
# subarray of size K
xorr = 0
for it in st:
xorr = (xorr ^ it)
# update mx
mx = max(mx, xorr)
# Returning the Maximum XOR of subarray
# of size K with all distinct
return mx
# Driver function
if __name__ == "__main__":
# Size of given subarray
N = 10
# Given array A
A = [2, 3, 4, 2, 4, 5, 7, 4, 3, 9]
# Size of subarray needed
K = 4
# Function Call
print("Maximum XOR of subarray of size K with all distincts are : ", maximumXorsubarray(N, A, K))
# This code is contributed by lokeshpotta20.
C#
// C# code for the above approach
using System;
using System.Collections.Generic;
public class GFG {
// Function performing Calculation
static int MaximumXorSubarray(int N, int[] A, int K)
{
// Variable for storing maximum XOR of the subarray
// of size K
int mx = -1;
// Generating all subarray of size K
for (int i = 0; i < N - K + 1; i++)
{
// Set is used for storing the element of
// subarray and checking distinct condition
HashSet<int> st = new HashSet<int>();
for (int j = i; j < i + K; j++) {
st.Add(A[j]);
}
// If subarray is of size K with all distinct
if (st.Count == K)
{
// Calculating xor of the subarray of size K
int xorr = 0;
foreach(int it in st)
{
xorr = (xorr ^ it);
}
// update mx
mx = Math.Max(mx, xorr);
}
}
// Returning the Maximum XOR of subarray of size K
// with all distinct
return mx;
}
static public void Main()
{
// Code
// Size of given subarray
int N = 10;
// Given array A
int[] A = { 2, 3, 4, 2, 4, 5, 7, 4, 3, 9 };
// Size of subarray needed
int K = 4;
// Function Call
Console.WriteLine(
"Maximum XOR of subarray of size K with all distincts are : "
+ MaximumXorSubarray(N, A, K));
}
}
// This code is contributed by sankar.
JavaScript
// Function performing Calculation
function maximumXorsubarray(N, A, K) {
// Variable for storing maximum XOR
// of the subarray of size K
let mx = -1;
// Generating all subarray of size K
for (let i = 0; i <= N - K; i++) {
// Set is used for storing the
// element of subarray and
// checking distinct condition
let st = new Set();
for (let j = i; j < i + K; j++) {
st.add(A[j]);
}
// If subarray is of size K with
// all distinct
if (st.size === K) {
// Calculating xor of the
// subarray of size K
let xorr = 0;
for (let it of st) {
xorr = (xorr ^ it);
}
// update mx
mx = Math.max(mx, xorr);
}
}
// Returning the Maximum XOR of subarray
// of size K with all distinct
return mx;
}
// Driver function
const N = 10;
const A = [2, 3, 4, 2, 4, 5, 7, 4, 3, 9];
const K = 4;
// Function Call
console.log("Maximum XOR of subarray of size K with all distincts are : ", maximumXorsubarray(N, A, K));
OutputMaximum XOR of subarray of size K with all distincts are : 9
Time Complexity: O(N*K)
Auxiliary Space: O(K)
Efficient Approach: To solve the problem follow the below idea:
In this approach, we will use the XOR property that ( X XOR X ) is 0 and we have to take a map that will store the frequencies of the integers and use the 2-pointer approach, whenever we get the element whose frequency exceeds 1 or whenever the size of the map will exceed K then we will shrink window otherwise we will expand the window.
Below is the implementation of the above approach:
C++
// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
// Function performing Calculation
int maximumXorsubarray(int N, vector<int>& A, int K)
{
// Variable for storing maximum XOR
// of the subarray of size K
int mx = -1;
// Declaring map which is used for
// storing frequencies
map<int, int> mp;
// Temporary variable
int xorr = 0;
// Using 2-pointers i, j
int i = 0;
for (int j = 0; j < N; j++) {
// Expanding the window
mp[A[j]]++;
xorr = (xorr xor A[j]);
// Shrinking the window
while (mp[A[j]] > 1 || mp.size() > K) {
mp[A[i]]--;
xorr = (xorr xor A[i]);
if (mp[A[i]] == 0)
mp.erase(A[i]);
i++;
}
// If size of window is equal to K
// then updating the mx variable
if ((j - i + 1) == K) {
mx = max(mx, xorr);
}
}
// Returning the Maximum XOR of subarray
// of size K with all distinct
return mx;
}
// Driver function
int main()
{
// Size of given subarray
int N = 10;
// Given array A
vector<int> A = { 2, 3, 4, 2, 4, 5, 7, 4, 3, 9 };
// Size of subarray needed
int K = 4;
// Function Call
cout << "Maximum XOR of subarray of size K with all "
"distinct are : "
<< maximumXorsubarray(N, A, K);
return 0;
}
Java
// Java code for the above approach:
import java.util.*;
class GFG {
// Function performing Calculation
static int maximumXorsubarray(int N, int[] A, int K) {
// Variable for storing maximum XOR
// of the subarray of size K
int mx = -1;
// Declaring map which is used for
// storing frequencies
Map<Integer, Integer> mp = new HashMap<>();
// Temporary variable
int xorr = 0;
// Using 2-pointers i, j
int i = 0;
for (int j = 0; j < N; j++) {
// Expanding the window
mp.put(A[j], mp.getOrDefault(A[j], 0) + 1);
xorr = xorr ^ A[j];
// Shrinking the window
while (mp.get(A[j]) > 1 || mp.size() > K) {
int count = mp.get(A[i]);
count--;
if (count == 0) {
mp.remove(A[i]);
} else {
mp.put(A[i], count);
}
xorr = xorr ^ A[i];
i++;
}
// If size of window is equal to K
// then updating the mx variable
if ((j - i + 1) == K) {
mx = Math.max(mx, xorr);
}
}
// Returning the Maximum XOR of subarray
// of size K with all distinct
return mx;
}
// Driver function
public static void main(String[] args) {
// Size of given subarray
int N = 10;
// Given array A
int[] A = {2, 3, 4, 2, 4, 5, 7, 4, 3, 9};
// Size of subarray needed
int K = 4;
// Function Call
System.out.println("Maximum XOR of subarray of size K with all " +
"distinct are: " + maximumXorsubarray(N, A, K));
}
}
// This Code is Contributed by Prasad Kandekar(prasad264)
C#
// C# code for the above approach:
using System;
using System.Collections.Generic;
public class GFG {
// Function performing Calculation
static int maximumXorsubarray(int N, int[] A, int K)
{
// Variable for storing maximum XOR
// of the subarray of size K
int mx = -1;
// Declaring map which is used for
// storing frequencies
Dictionary<int, int> mp
= new Dictionary<int, int>();
// Temporary variable
int xorr = 0;
// Using 2-pointers i, j
int i = 0;
for (int j = 0; j < N; j++) {
// Expanding the window
if (mp.ContainsKey(A[j])) {
mp[A[j]]++;
}
else {
mp[A[j]] = 1;
}
xorr = xorr ^ A[j];
// Shrinking the window
while (mp[A[j]] > 1 || mp.Count > K) {
int count = mp[A[i]];
count--;
if (count == 0) {
mp.Remove(A[i]);
}
else {
mp[A[i]] = count;
}
xorr = xorr ^ A[i];
i++;
}
// If size of window is equal to K
// then updating the mx variable
if ((j - i + 1) == K) {
mx = Math.Max(mx, xorr);
}
}
// Returning the Maximum XOR of subarray
// of size K with all distinct
return mx;
}
static public void Main()
{
// Code
// Size of given subarray
int N = 10;
// Given array A
int[] A = { 2, 3, 4, 2, 4, 5, 7, 4, 3, 9 };
// Size of subarray needed
int K = 4;
// Function Call
Console.WriteLine(
"Maximum XOR of subarray of size K with all "
+ "distinct are: "
+ maximumXorsubarray(N, A, K));
}
}
// This code is contributed by karthik.
Python3
def maximumXorsubarray(N, A, K):
# Variable for storing maximum XOR
# of the subarray of size K
mx = -1
# Declaring map which is used for
# storing frequencies
mp = {}
# Temporary variable
xorr = 0
# Using 2-pointers i, j
i = 0
for j in range(N):
# Expanding the window
if A[j] not in mp:
mp[A[j]] = 0
mp[A[j]] += 1
xorr ^= A[j]
# Shrinking the window
while mp[A[j]] > 1 or len(mp) > K:
mp[A[i]] -= 1
xorr ^= A[i]
if mp[A[i]] == 0:
mp.pop(A[i])
i += 1
# If size of window is equal to K
# then updating the mx variable
if j - i + 1 == K:
mx = max(mx, xorr)
# Returning the Maximum XOR of subarray
# of size K with all distinct
return mx
# Size of given subarray
N = 10
# Given array A
A = [2, 3, 4, 2, 4, 5, 7, 4, 3, 9]
# Size of subarray needed
K = 4
# Function Call
print("Maximum XOR of subarray of size K with all "
"distinct are: ", maximumXorsubarray(N, A, K))
JavaScript
// JavaScript code for the above approach:
function maximumXorsubarray(N, A, K)
{
// Variable for storing maximum XOR
// of the subarray of size K
let mx = -1;
// Declaring map which is used for
// storing frequencies
let mp = new Map();
// Temporary variable
let xorr = 0;
// Using 2-pointers i, j
let i = 0;
for (let j = 0; j < N; j++) {
// Expanding the window
mp.set(A[j], (mp.get(A[j]) || 0) + 1);
xorr ^= A[j];
// Shrinking the window
while (mp.get(A[j]) > 1 || mp.size > K) {
mp.set(A[i], mp.get(A[i]) - 1);
xorr ^= A[i];
if (mp.get(A[i]) == 0)
mp.delete(A[i]);
i++;
}
// If size of window is equal to K
// then updating the mx variable
if (j - i + 1 == K) {
mx = Math.max(mx, xorr);
}
}
// Returning the Maximum XOR of subarray
// of size K with all distinct elements
return mx;
}
// Driver function
const N = 10;
// Given array A
const A = [ 2, 3, 4, 2, 4, 5, 7, 4, 3, 9 ];
// Size of subarray needed
const K = 4;
// Function Call
console.log("Maximum XOR of subarray of size K with all distinct elements is: "
+ maximumXorsubarray(N, A, K));
OutputMaximum XOR of subarray of size K with all distict are : 9
Time Complexity: O(N*Log(K))
Auxiliary Space: O(K)
Similar Reads
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
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
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
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
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
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
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read