XOR Queries of a Subarray in C++


Suppose we have the array arr of positive integers and the array queries where queries[i] = [Li, Ri], for each query the i compute the XOR of elements from Li to Ri (that is, arr[Li] XOR arr[Li+1] xor ... xor arr[Ri] ). We have to find the array containing the result for the given queries. So if the input is like − [1,3,4,8], and queries are like [[0,1],[1,2],[0,3],[3,3]], then the result will be [2,7,14,8]. This is because the binary representation of the elements in the array are − 1 = 0001, 3 = 0011, 4 = 0100 and 8 = 1000. Then the XOR values for queries are − [0,1] = 1 xor 3 = 2, [1,2] = 3 xor 4 = 7, [0,3] = 1 xor 3 xor 4 xor 8 = 14 and [3,3] = 8

To solve this, we will follow these steps −

  • n := size of arr
  • define an array called pre, of size n + 1, then fill pre, such that pre[i] := pre[i – 1] XOR arr[i – 1]
  • Define another array ans
  • for i in range 0 to number of queries – 1
    • l := queries[i, 0], r := queries[i, 1]
    • increase l and r by 1
    • insert pre[r] XOR pre[l - 1], into ans
  • return ans

Example(C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   vector<int> xorQueries(vector<int>& arr, vector<vector<int>>& queries) {
      int n = arr.size();
      vector <int> pre(n + 1);
      for(int i = 1; i <=n; i++){
         pre[i] = pre[i - 1] ^ arr[i - 1];
      }
      vector <int> ans;
      for(int i = 0; i < queries.size(); i++){
         int l = queries[i][0];
         int r = queries[i][1];
         l++;
         r++;
         ans.push_back(pre[r] ^ pre[l - 1]);
      }
      return ans;
   }
};
main(){
   vector<int> v = {1,3,4,8};
   vector<vector<int>> v1 = {{0,1},{1,2},{0,3},{3,3}};
   Solution ob;
   print_vector(ob.xorQueries(v, v1));
}

Input

[1,3,4,8]
[[0,1],[1,2],[0,3],[3,3]]

Output

[2,7,14,8]

Updated on: 30-Apr-2020

178 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements