Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Subarrays with XOR ‘K’

Easy
0/40
Average time to solve is 20m
profile
Contributed by
147 upvotes

Problem statement

Given an array ‘A’ consisting of ‘N’ integers and an integer ‘B’, find the number of subarrays of array ‘A’ whose bitwise XOR( ⊕ ) of all elements is equal to ‘B’.


A subarray of an array is obtained by removing some(zero or more) elements from the front and back of the array.


Example:
Input: ‘N’ = 4 ‘B’ = 2
‘A’ = [1, 2, 3, 2]

Output: 3

Explanation: Subarrays have bitwise xor equal to ‘2’ are: [1, 2, 3, 2], [2], [2].
Detailed explanation ( Input/output format, Notes, Images )
Input Format
The first line contains two integers, ‘N’ and ‘B’, denoting the size of the array ‘A’ and integer ‘B’, respectively.
The following line contains ‘N’ integers, denoting the ‘A’.
Output format:
Return the number of subarrays of array ‘A’ whose bitwise xor of all elements is equal to ‘B’.
Note:-
You don't need to print anything. Just implement the given function.
Sample Input 1:
4 2
1 2 3 2
Sample Output 1 :
3
Explanation Of Sample Input 1:
Input: ‘N’ = 4 ‘B’ = 2
‘A’ = [1, 2, 3, 2]

Output: 3

Explanation: Subarrays have bitwise xor equal to ‘2’ are: [1, 2, 3, 2], [2], [2].
Sample Input 2:
4 3
1 2 3 3
Sample Output 2:
4
Sample Input 3:
5 6
1 3 3 3 5 
Sample Output 3:
2
Constraints:
1 <= N <= 10^3
1 <= A[i], B <= 10^9

Time Limit: 1-sec
Hint

Use nested loops to calculate the xor of every subarray.

Approaches (2)
Brute Force

The approach is to generate all the subarrays of array ‘A’ using two loops, one nested into the other. 

For each generated subarray, we will calculate the respective XOR and then check whether the XOR is equal to ‘B’. If true, then we will increase the count. 

In the end, we will get the total number of all subarrays whose XOR is equal to ‘B’.

 

The steps are as follows:-

 

// Function to find the Subarrays with XOR ‘K’

            function subarraysWithSumK(int[] A, int N, int B):
 

  1. Int 'N' be the size of arrays ‘A’ and int ‘B’ be the required XOR, respectively.
  2. Initialize an integer ‘count’ to 0, storing the number of subarrays whose XOR is equal to ‘B’.
  3. Iterate over array ‘A’ from index ‘0’ to index ‘N - 1’ using variable ‘i’:
    • Initialize an integer ‘curr’ to 0, storing the bitwise XOR of the current subarray.
    • Iterate over array ‘A’ from index ‘i’ to index ‘N - 1’ using variable ‘j’:
      • Assign ‘curr’ to ‘curr xor A[j]’.
      • If ‘curr’ == ‘B’:
        • Increment the ‘count’ variable.
  4. Return ‘count’.
Time Complexity

O( N ^ 2 ), where 'N' is the size of Array ‘A’.
 

We are using nested loops.

 

Hence the time complexity is O( N ^ 2 ).

Space Complexity

O( 1 ).
 

We are only using some variables to store the current XOR, and count.

 

Hence the space complexity is O( 1 ).

Code Solution
(100% EXP penalty)
Subarrays with XOR ‘K’
All tags
Sort by
Search icon

Interview problems

Oh Man it's so frustrating , in Java it is showing ,cannot find symbol Map xorMap = new HashMap<>(); // storing the

HashMap<Integer,Integer> xorMap = new HashMap<>();
4 views
1 reply
0 upvotes

Interview problems

Count the number of subarrays with given xor K optimal solution🪜☄️📌

What the Program Does:

  • The program finds how many subarrays in a given list of numbers have an XOR value that matches a target value b.

XOR Basics:

  • XOR is a bitwise operation that compares the binary form of two numbers. When the bits are different, the XOR result is 1, and when they're the same, the result is 0.
  • Example: 5 ^ 3 compares the bits of 5 (101) and 3 (011), resulting in 110, which is 6.

Steps in the Program:

  • The program goes through each number in the array one by one.
  • As it goes, it keeps track of the XOR of all the numbers it has seen so far.
  • At each step, it checks if there's a previous subarray whose XOR, when combined with the current XOR, gives the target value b.

Using a Map:

  • The program uses a "map" (or dictionary) to remember how many times each XOR result has appeared. This helps quickly check if there’s a subarray that matches the XOR we want.

Counting Matches:

  • Whenever it finds a match, meaning it found a subarray that XORs to b, it increases the count.

Final Result:

  • After checking all the numbers, it returns the total number of subarrays whose XOR matches b.
Simple Analogy:

Think of it like a treasure hunt 🏴‍☠️. As you explore each number in the array, you keep a running total of your "XOR treasure points." You also remember all the "points" you’ve gathered along the way in a notebook (the map). Whenever you see that the points you’ve just gathered, plus what you’ve already written down, match the treasure target b, you celebrate 🎉 and increase your count of found treasures.

In the end, you tell how many treasures (subarrays) you found that have exactly the right amount of points (XOR equals b).

 

import java.util.*;
public class Solution {
    public static int subarraysWithSumK(int []a, int b) {
        // Write your code here
   
 int size=a.length;
    int count=0;
    Map<Integer,Integer>hm=new HashMap<>();
    hm.put(0,1);
    int xor=0;
    for(int i=0;i<size;i++)
    {
        xor=xor^a[i];
        int x=xor^b;
        if(hm.containsKey(x))
        count=count+hm.get(x);
        
        hm.put(xor,hm.getOrDefault(xor, 0)+1);
    }
    return count;
    }
}
14 views
0 replies
0 upvotes

Interview problems

C++ || Optimal Solution 🔥🔥

#include<bits/stdc++.h>

int subarraysWithSumK(vector < int > a, int b) {

    // Write your code here

    int n = a.size();

    int cnt = 0;

    unordered_map<int,int> mpp;

    mpp[0] = 1;

    int xr = 0;

 

    for(int i=0;i<n;i++){

        xr = xr^a[i];

        int x = xr^b;

        cnt += mpp[x];

        mpp[xr]++;

    }

 

    return cnt;

}

84 views
0 replies
0 upvotes

Interview problems

Simplest and easy to understand!

#include<bits/stdc++.h>
int subarraysWithSumK(vector < int > a, int b) {
    // Write your code here
    unordered_map<int,int>mp;
    int cnt=0;
    int ans=0;
    for(int i=0;i<a.size();i++){
        ans^=a[i];
        if(ans==b){
            cnt++;
        }
        if(mp.find(b^ans)!=mp.end()){
            cnt+=mp[b^ans];
        }
        mp[ans]++;
    }
    return cnt;
}
44 views
0 replies
1 upvote

Interview problems

EASY Approach || same as subarray sum equals k || MAP

int subarraysWithSumK(vector < int > a, int k) {

    unordered_map<int,int> m;

    int cnt=0;

    m[0]=1;

    int xr=0;

    for(int i=0;i<a.size();i++){

        xr=xr^a[i];

        if(m[xr^k]){

            cnt+=m[xr^k];

        }

        m[xr]++;

    }

    return cnt;

}

51 views
0 replies
0 upvotes

Interview problems

easy c++ code, optimal one

#include<bits/stdc++.h>

int subarraysWithSumK(vector<int>a,int b) {

   map<int,int>mpp;

   int xorr = 0;

   mpp[0] = 1;

   int count = 0;

   for(int i=0;i<a.size();i++) {

       xorr = xorr^a[i];

       int x = xorr^b;

       count += mpp[x];

       mpp[xorr]++;

   }

   return count;

}

36 views
0 replies
0 upvotes

Interview problems

C++ Solution || All test case passed || Time Complexity: O(n * log n)

#include <bits/stdc++.h>
int subarraysWithSumK(vector<int> a, int b) {

    int xr = 0, n = a.size();
    map<int, int> preXors;
    preXors[xr]++;
    int cnt = 0;

    for (int i = 0; i < n; i++) {

        xr ^= a[i];
        int remXr = xr ^ b;

        cnt += preXors[remXr];

        preXors[xr]++;

    }

    return cnt;
}
89 views
0 replies
1 upvote

Interview problems

best solution to this problem...

we know that if a^b = c then a^c = b or b^c = a therefore we just have to exploit this knowledge to solve :  

//solution

 

int subarraysWithSumK(vector < int > a, int b) {

    int xr = 0; //here xr will store previous xor values

    unordered_map<int,int> mp;

    mp[xr]++; //step 1 insert {0,1} in the map

    int cnt = 0;

    int n = a.size();

    for(int i=0; i<n; i++){

        xr = xr ^ a[i]; // will get the latest xor of prev arr elements

        int x = xr ^ b; 

        cnt += mp[x];

        mp[xr]++;

    }

    return cnt;

}

programming

38 views
0 replies
0 upvotes

Interview problems

Simple Cpp Solution| TC= O(nlogn)|

#include<bits/stdc++.h>

int subarraysWithSumK(vector < int > a, int b) {

    // Write your code here

   int c=0;

   int n=a.size();

   map<int,int> mpp;

   int temp=0;

   for(int i=0;i<n;i++)

   {

       temp^=a[i];

       if(temp==b)c++;

       int rem=temp^b;

       if(mpp.find(rem)!=mpp.end())

       {

           c+=mpp[rem];

       }

       mpp[temp]++;

    }

  return c;

}

77 views
0 replies
2 upvotes

Interview problems

java optimal solution

import java.util.*;

 

public class Solution {

    public static int subarraysWithSumK(int []a, int b) {

        // Write your code here

        int cnt=0;

        int n = a.length;

          int  xor =0;

          Map<Integer,Integer>mpp=new HashMap<>();

          mpp.put(xor,1);

        for(int i=0;i<n;i++)

        {

            xor = xor^a[i];

            int x=xor^b;

            if(mpp.containsKey(x))

            {

                cnt+=mpp.get(x);

            }

            if(mpp.containsKey(xor))

            {

                mpp.put(xor,mpp.get(xor)+1);

            }

            else

            {

                mpp.put(xor,1);

            }

        }

        return cnt;

    }

}

89 views
0 replies
1 upvote
Full screen
Console