C++ program to find number of l-r pairs for which XORed results same as summation


Suppose we have an array A with N elements. We have to find the number of pairs of integers l and r that satisfies A[l] XOR A[l+1] XOR ... XOR A[r-1] XOR A[r] = A[l] + A[l+1] + ... A[r].

So, if the input is like A = [2, 5, 4, 6], then the output will be 5, because for pairs (1,1), (2,2), (3,3), (4,4) and (1,2).

Steps

To solve this, we will follow these steps −

n := size of A
Define some arrays of size (n + 1) each, a, s and sx
for initialize i := 1, when i <= n, update (increase i by 1), do:
   a[i] := A[i - 1]
   s[i] := s[i - 1] + a[i]
   sx[i] := sx[i - 1] XOR a[i]
res := 0
for initialize l := 1, when l <= n, update (increase l by 1), do:
   bg := l, en = n, r = l
   while bg <= en, do:
      mi := (bg + en) / 2
      if s[mi] - s[l - 1] is same as (sx[mi] XOR sx[l - 1]), then:
         r := mi
         bg := mi + 1
      Otherwise
         en := mi - 1
      res := res + (r - l + 1)
return res

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

int solve(vector<int> A){
   int n = A.size();
   vector<int> a(n + 1), s(n + 1), sx(n + 1);
   for (int i = 1; i <= n; i++){
      a[i] = A[i - 1];
      s[i] = s[i - 1] + a[i];
      sx[i] = sx[i - 1] ^ a[i];
   }
   int res = 0;
   for (int l = 1; l <= n; l++){
      int bg = l, en = n, r = l;
      while (bg <= en){
         int mi = (bg + en) / 2;
         if (s[mi] - s[l - 1] == (sx[mi] ^ sx[l - 1])){
            r = mi;
            bg = mi + 1;
         }
         else
            en = mi - 1;
      }
      res += (r - l + 1);
   }
   return res;
}
int main(){
   vector<int> A = { 2, 5, 4, 6 };
   cout << solve(A) << endl;
}

Input

{ 2, 5, 4, 6 }

Output

5

Updated on: 03-Mar-2022

77 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements