Subarray with XOR less than k

• Difficulty Level : Expert
• Last Updated : 28 Apr, 2021

Given an array of n numbers and a number k. You have to write a program to find the number of subarrays with xor less than k.
Examples:

Input:  arr[] = {8, 9, 10, 11, 12},  k=3
Output: 4
Sub-arrays [1:3], [2:3], [2:5], [4:5] have xor
values 2, 1, 0, 1 respectively.

Input: arr[] = {12, 4, 6, 8, 21},  k=8
Output: 4

Naive Approach: The naive algorithm is to simply calculate the xor value of each and every subarray and compare with the given number k to find the answer.
Below is implementation of this approach:

C++

 // C++ program to count number of// subarrays with XOR less than k#include using namespace std; // function to count number of// subarrays with XOR less than kint xorLessK(int arr[], int n, int k){    int count = 0;     // check all subarrays    for (int i = 0; i < n; i++) {        int tempXor = 0;        for (int j = i; j < n; j++) {            tempXor ^= arr[j];            if (tempXor < k)                count++;        }    }     return count;} // Driver program to test above functionint main(){    int n, k = 3;    int arr[] = { 8, 9, 10, 11, 12 };     n = sizeof(arr) / sizeof(arr);     cout << xorLessK(arr, n, k);     return 0;}

Java

 // Java program to count number of// subarrays with XOR less than k import java.io.*; class GFG {     // function to count number of// subarrays with XOR less than kstatic int xorLessK(int arr[], int n, int k){    int count = 0;     // check all subarrays    for (int i = 0; i < n; i++) {        int tempXor = 0;        for (int j = i; j < n; j++) {            tempXor ^= arr[j];            if (tempXor < k)                count++;        }    }     return count;} // Driver program to test above function    public static void main (String[] args) {              int k = 3;    int arr[] = new int[] { 8, 9, 10, 11, 12 };    int n = arr.length;     System.out.println(xorLessK(arr, n, k));             }}

Python3

 # Python 3 program to count number of# subarrays with XOR less than k # function to count number of# subarrays with XOR less than kdef xorLessK(arr, n, k):    count = 0     # check all subarrays    for i in range(n):        tempXor = 0        for j in range(i, n):            tempXor ^= arr[j]            if (tempXor < k):                count += 1         return count # Driver Codeif __name__ == '__main__':    k = 3    arr = [8, 9, 10, 11, 12]     n = len(arr)     print(xorLessK(arr, n, k)) # This code is contributed by# Sahil_shelangia

C#

 // C# program to count number of// subarrays with XOR less than kusing System; class GFG {     // function to count number of// subarrays with XOR less than kstatic int xorLessK(int []arr, int n, int k){    int count = 0;     // check all subarrays    for (int i = 0; i < n; i++) {                 int tempXor = 0;                 for (int j = i; j < n; j++) {                         tempXor ^= arr[j];            if (tempXor < k)                count++;        }    }     return count;} // Driver Codestatic public void Main (){             int k = 3;    int []arr = new int[] {8, 9, 10,                           11, 12 };    int n = arr.Length;    Console.WriteLine(xorLessK(arr, n, k));     }}



Javascript



Output:

3

Time Complexity Efficient Approach: An efficient approach will be to calculate all of the prefix xor values i.e. a[1:i] for all i.
It can be verified that the xor of a subarray a[l:r] can be written as (a[1:l-1] xor a[1:r]), where a[i, j] is the xor of all the elements with index such that, i <= index <= j.
Explanation:
We will store a number as binary number in trie. The left child will shows that the next bit is 0 and the right child will show the next bit is 1.
For example, given picture below shows number 1001 and 1010 in trie. If xor[i, j] represents the xor of all elements in the subarray a[i, j], then at an index i what we have is, a trie which has xor[1:1], xor[1:2]…..xor[1:i-1] already inserted. Now we somehow count how many of these (numbers in trie) are such that its xor with xor[1:i] is smaller than k. This will cover all the subarrays ending at the index i and having xor i.e. xor[j, i] <=k;
Now the problem remains, how to count the numbers with xor smaller than k. So, for example take the current bit of the ith index element is p, current bit of number k be q and the current node in trie be node.
Take the case when p=1, k=1. Then if we go to the right child the current xor would be 0 (as the right child means 1 and p=1, 1(xor)1=0).As k=1, all the numbers that are to the right child of this node would give xor value smaller than k. So, we would count the numbers that are right to this node.
If we go to the left child, the current xor would be 1 (as the left child means 0 and p=1, 0(xor)1=1). So, if we go to the left child we can still find number with xor smaller than k, therefore we move on to the left child.
So, to count the numbers that are below a given node, we modify the trie and each node will also store the number of leafs in that subtree and this would be modified after each insertion.
Other three cases for different values of p and k can be solved in the same way to the count the number of numbers with xor less than k.
Below is the C++ implementation of above idea:

CPP

Output:

4

Time complexity: O(n*log(max)), where max is the maximum element in the array.
Related Articles

This article is contributed by Amritya Vagmi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.