- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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 −

#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

- Related Questions & Answers
- Minimum flips in two binary arrays so that their XOR is equal to another array in C++.
- Count ways to form minimum product triplets in C++
- Count Triplets such that one of the numbers can be written as sum of the other two in C++
- Count number of triplets with product equal to given number in C++
- Count minimum bits to flip such that XOR of A and B equal to C in C++
- Print all triplets in sorted array that form AP in C++
- Count pairs from two arrays having sum equal to K in C++
- Checking if two arrays can form a sequence - JavaScript
- Count of sub-arrays whose elements can be re-arranged to form palindromes in C++
- Maximum value of XOR among all triplets of an array in C++
- Equal Sum and XOR in C++
- Count number of triplets with product equal to given number with duplicates allowed in C++
- Count all triplets whose sum is equal to a perfect cube in C++
- Find sub-arrays from given two arrays such that they have equal sum in Python
- Count all Quadruples from four arrays such that their XOR equals to ‘x’ in C++