Count Triplets That Can Form Two Arrays of Equal XOR in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of integers arr. We want to select three indices like i, j and k where (0 <= i < j <= k < N), N is the size of array. The values of a and b are as follows: a = arr[i] XOR arr[i + 1] XOR ... XOR arr[j - 1] b = arr[j] XOR arr[j + 1] XOR ... XOR arr[k] We have to find the number of triplets (i, j, k) Where a is same as b.

So, if the input is like [2,3,1,6,7], then the output will be 4, as the triplets are (0,1,2), (0,2,2), (2,3,4) and (2,4,4)

To solve this, we will follow these steps −

  • ret := 0

  • n := size of arr

  • for initialize i := 1, when i < n, update (increase i by 1), do −

    • Define one map m

    • x1 := 0, x2 := 0

    • for initialize j := i - 1, when j >= 0, update (decrease j by 1), do −

      • x1 := x1 XOR arr[j]

      • (increase m[x1] by 1)

    • for initialize j := i, when j < n, update (increase j by 1), do −

      • x2 := x2 XOR arr[j]

      • ret := ret + m[x2]

  • return ret

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int countTriplets(vector<int>& arr) {
      int ret = 0;
      int n = arr.size();
      for (int i = 1; i < n; i++) {
         map<int, int> m;
         int x1 = 0;
         int x2 = 0;
         for (int j = i - 1; j >= 0; j--) {
            x1 = x1 ^ arr[j];
            m[x1]++;
         }
         for (int j = i; j < n; j++) {
            x2 = x2 ^ arr[j];
            ret += m[x2];
         }
      }
      return ret;
   }
};
main(){
   Solution ob;
   vector<int> v = {2,3,1,6,7};
   cout << (ob.countTriplets(v));
}

Input

{2,3,1,6,7}

Output

4
raja
Published on 17-Nov-2020 12:20:19
Advertisements