# Count all triplets from given Array whose bitwise XOR is equal to K

Given an array arr[] which contains N positive integers and an integer K. The task is to count all triplets whose XOR is equal to the K. i.e arr[ i ] ^ arr[ j ] ^ arr[ k ] = X where 0 â‰¤ i < j < k < N ( 0 based indexing)

Examples:

Input: arr[] = { 2, 1, 3, 7, 5, 4}, K = 5
Output: 2
Explanation: In the above array there are two triplets whose xor is equal to K
{ 2, 3, 4}, ( 2 ^ 3 ^ 4 = 5)
{1, 3, 7}, ( 1 ^ 3 ^ 7 = 5 )
So, output is 2.

Input: arr[] = { 4, 1, 5, 7}, X=0
Output:1
Explanation: In the above array there is only one triplet whose xor is equal to K
{ 4, 1, 5} (4 ^ 1 ^ 5=0)

Naive Approach: A simple approach is to check every triplet, if it’s bitwise xor is equal to K then increase the count by 1.
And finally, return the count.

Below is the implementation of the above approach:

## C++

 `// C++ code to implement the above approach`   `#include ` `using` `namespace` `std;`   `// Count of all valid triplets` `int` `count_triplets(``int` `arr[], ``int` `N, ``int` `K)` `{` `    ``int` `cnt = 0;`   `    ``// Fixed first element as arr[i]` `    ``for` `(``int` `i = 0; i < N; i++) {`   `        ``// Fixed second element as arr[j]` `        ``for` `(``int` `j = i + 1; j < N; j++) {`   `            ``// Now look for third element` `            ``for` `(``int` `k = j + 1; k < N; k++) {` `                ``int` `triplet_xor = arr[i] ^ arr[j] ^ arr[k];`   `                ``// If xor is equal to K` `                ``// increase cnt by 1.` `                ``if` `(triplet_xor == K) {` `                    ``cnt++;` `                ``}` `            ``}` `        ``}` `    ``}` `    ``return` `cnt;` `}`   `// Driver code` `int` `main()` `{` `    ``int` `N = 6;` `    ``int` `arr[] = { 2, 1, 3, 7, 5, 4 };` `    ``int` `K = 5;`   `    ``// Function call` `    ``cout << count_triplets(arr, N, K);` `    ``return` `0;` `}`

## C

 `// C code to implement the approach`   `#include `   `// Function to count of all valid triplets` `int` `count_triplets(``int` `arr[], ``int` `N, ``int` `K)` `{` `    ``int` `cnt = 0;`   `    ``// Fixed first element as arr[i]` `    ``for` `(``int` `i = 0; i < N; i++) {`   `        ``// Fixed second element as arr[j]` `        ``for` `(``int` `j = i + 1; j < N; j++) {`   `            ``// Now look for third element` `            ``for` `(``int` `k = j + 1; k < N; k++) {` `                ``int` `triplet_xor` `                    ``= arr[i] ^ arr[j] ^ arr[k];`   `                ``// If xor is equal to X` `                ``// increase cnt by 1.` `                ``if` `(triplet_xor == K) {` `                    ``cnt++;` `                ``}` `            ``}` `        ``}` `    ``}` `    ``return` `cnt;` `}`   `// Driver code` `int` `main()` `{` `    ``int` `N = 6;` `    ``int` `arr[] = { 2, 1, 3, 7, 5, 4 };` `    ``int` `K = 5;`   `    ``// Function call` `    ``printf``(``"%d"``, count_triplets(arr, N, K));` `    ``return` `0;` `}`

## Java

 `// Java code to implement the approach`   `import` `java.util.*;`   `class` `FindTriplet {`   `    ``// Function to count all triplets` `    ``int` `count_triplets(``int` `arr[], ``int` `N, ``int` `K)` `    ``{` `        ``int` `cnt = ``0``;`   `        ``// Fix the first element as arr[i]` `        ``for` `(``int` `i = ``0``; i < N; i++) {`   `            ``// Fix the second element as arr[j]` `            ``for` `(``int` `j = i + ``1``; j < N; j++) {`   `                ``// Now look for the third number` `                ``for` `(``int` `k = j + ``1``; k < N;` `                     ``k++) {` `                    ``int` `triplet_xor` `                        ``= arr[i] ^ arr[j]` `                          ``^ arr[k];`   `                    ``// If xor is equal to X` `                    ``// increase cnt by 1.` `                    ``if` `(triplet_xor == K) {` `                        ``cnt++;` `                    ``}` `                ``}` `            ``}` `        ``}`   `        ``return` `cnt;` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``FindTriplet triplet = ``new` `FindTriplet();` `        ``int` `N = ``6``;` `        ``int` `arr[] = { ``2``, ``1``, ``3``, ``7``, ``5``, ``4` `};` `        ``int` `K = ``5``;`   `        ``// Function call` `        ``System.out.print(triplet.count_triplets(arr, N, K));` `    ``}` `}`

## Python3

 `# Python3 code for the above approach`   `# Count of all valid triplets` `def` `count_triplets(arr, N, K):`   `    ``cnt ``=` `0`   `    ``# Fixed first element as arr[i]` `    ``for` `i ``in` `range``(N):` `      `  `        ``# Fixed second element as arr[j]` `        ``for` `j ``in` `range``(i ``+` `1``, N):` `          `  `            ``# Now look for third element` `            ``for` `k ``in` `range``(j ``+` `1``, N):` `                ``triplet_xor ``=` `arr[i] ^ arr[j] ^ arr[k]` `                `  `                ``# If xor is equal to K` `                ``# increase cnt by 1.` `                ``if` `triplet_xor ``=``=` `K:` `                    ``cnt ``+``=` `1`   `    ``return` `cnt`   `# Driver code` `N ``=` `6` `arr ``=` `[``2``, ``1``, ``3``, ``7``, ``5``, ``4``]` `K ``=` `5`   `# function call` `print``(count_triplets(arr, N, K))`   `# This code was contributed by phasing17`

## C#

 `// C# code to implement the approach` `using` `System;`   `class` `GFG ` `{`   `  ``// Function to count all triplets` `  ``static` `int` `count_triplets(``int``[] arr, ``int` `N, ``int` `K)` `  ``{` `    ``int` `cnt = 0;`   `    ``// Fix the first element as arr[i]` `    ``for` `(``int` `i = 0; i < N; i++) {`   `      ``// Fix the second element as arr[j]` `      ``for` `(``int` `j = i + 1; j < N; j++) {`   `        ``// Now look for the third number` `        ``for` `(``int` `k = j + 1; k < N; k++) {` `          ``int` `triplet_xor` `            ``= arr[i] ^ arr[j] ^ arr[k];`   `          ``// If xor is equal to X` `          ``// increase cnt by 1.` `          ``if` `(triplet_xor == K) {` `            ``cnt++;` `          ``}` `        ``}` `      ``}` `    ``}`   `    ``return` `cnt;` `  ``}`   `  ``// Driver code` `  ``public` `static` `int` `Main()` `  ``{` `    ``int` `N = 6;` `    ``int``[] arr = ``new` `int``[] { 2, 1, 3, 7, 5, 4 };` `    ``int` `K = 5;`   `    ``// Function call` `    ``Console.Write(count_triplets(arr, N, K));` `    ``return` `0;` `  ``}` `}`   `// This code is contributed by Taranpreet`

## Javascript

 ``

Output

```2

```

Time Complexity: O(N3)
Auxiliary Space: O(1)

Efficient Approach 1: The problem can be efficiently solved by Hashmap (map in c++) and xor properties on the following idea:

`Create a map/hashmap to store the frequency of elements and run two nested loop to select two elements of the possible triplet. Then find the third element with the help of Xor property (if a ^ x = K then a ^ K = x). If we find the third element in the map we add frequency of third element to our answer.`

Follow the steps below to implement the idea:

1. It initializes a counter variable cnt to 0.
2. It initializes an unordered map mp to store the frequency of each element in the array.
3. It uses two nested loops to iterate through all possible pairs in the array.
4. For each pair, it calculates the XOR of the two elements and the XOR required to get k (let’s say temp).
5. If the required XOR value is present in the map, it increments the cnt variable by the frequency of the required XOR value.
6. After iterating through all possible pairs, it increments the frequency of the current element in the map.
7. After all possible pairs have been checked, the function returns the value of cnt.

Below is the implementation of the above approach:

## C++

 `// c++ code for above approach` `#include ` `using` `namespace` `std;`   `// Function for counting triplets` `int` `count_triplets(``int` `arr[], ``int` `N, ``int` `K) {` `  ``// cnt variable to count the triplets` `    ``int` `cnt = 0;`   `  ``// map for storing the frequency of elements of the array` `    ``unordered_map<``int``, ``int``> mp;`   `    ``for` `(``int` `i = 0; i < N; i++) {` `        ``for` `(``int` `j = i + 1; j < N; j++) {` ` ``// Finding the third element         ` `            ``int` `temp = arr[i] ^ arr[j] ^ K;` `          `  ` ``// If third element is present in the map, increment the cnt       ` `            ``if` `(mp.find(temp) != mp.end()) {` `                ``cnt += mp[temp];` `            ``}` `        ``}` `      `  ` ``// increase the frequency of element in the map     ` `        ``mp[arr[i]]++;` `    ``}`   `    ``return` `cnt;` `}`   `// Driver code` `int` `main() {` `    ``int` `N = 6;` `    ``int` `arr[] = {2, 1, 3, 7, 5, 4};` `    ``int` `K = 5;`   `  ``// Function call` `    ``cout << count_triplets(arr, N, K);`   `    ``return` `0;` `}`

## Java

 `import` `java.util.HashMap;`   `public` `class` `GFG {` `  `  `      ``// Function for counting triplets` `    ``public` `static` `int` `count_triplets(``int``[] arr, ``int` `N, ``int` `K) {` `        ``// cnt variable to count the triplets` `          ``int` `cnt = ``0``;` `      `  `        ``// map for storing the frequency of elements of the array` `        ``HashMap mp = ``new` `HashMap<>();`   `        ``for` `(``int` `i = ``0``; i < N; i++) {` `            ``for` `(``int` `j = i + ``1``; j < N; j++) {` `                ``// Finding the third element ` `                ``int` `temp = arr[i] ^ arr[j] ^ K;` `                ``// If third element is present in the map, increment the cnt` `                ``if` `(mp.containsKey(temp)) {` `                    ``cnt += mp.get(temp);` `                ``}` `            ``}`   `              ``// increase the frequency of element in the map` `            ``if` `(mp.containsKey(arr[i])) {` `                ``mp.put(arr[i], mp.get(arr[i]) + ``1``);` `            ``} ``else` `{` `                ``mp.put(arr[i], ``1``);` `            ``}` `        ``}`   `        ``return` `cnt;` `    ``}`   `      ``// Driver  code` `    ``public` `static` `void` `main(String[] args) {` `        ``int` `N = ``6``;` `        ``int``[] arr = {``2``, ``1``, ``3``, ``7``, ``5``, ``4``};` `        ``int` `K = ``5``;`   `        ``System.out.println(count_triplets(arr, N, K));` `    ``}` `}`

## Python3

 `# Function for counting triplets` `def` `count_triplets(arr, N, K):` `    `  `    ``# cnt variable to count the triplets` `    ``cnt ``=` `0` `    `  `    ``# map for storing the frequency of elements of the array` `    ``mp ``=` `{}` `    ``for` `i ``in` `range``(N):` `        ``for` `j ``in` `range``(i ``+` `1``, N):` `          `  `              ``# Finding the third element  ` `            ``temp ``=` `arr[i] ^ arr[j] ^ K` `            `  `            ``#  If third element is present in the map, increment the cnt` `            ``if` `temp ``in` `mp:` `                ``cnt ``+``=` `mp[temp]` `                `  `        ``# increase the frequency of element in the map` `        ``mp[arr[i]] ``=` `mp.get(arr[i], ``0``) ``+` `1` `    ``return` `cnt` `# Driver code` `N ``=` `6` `arr ``=` `[``2``, ``1``, ``3``, ``7``, ``5``, ``4``]` `K ``=` `5`   `print``(count_triplets(arr, N, K))`

## C#

 `using` `System;` `using` `System.Collections.Generic;`   `class` `GFG` `{` `    ``// Function for counting triplets` `    ``public` `static` `int` `CountTriplets(``int``[] arr, ``int` `N, ``int` `K)` `    ``{` `        ``// cnt variable to count the triplets` `        ``int` `cnt = 0;`   `        ``// Dictionary for storing the frequency of elements of the array` `        ``Dictionary<``int``, ``int``> mp = ``new` `Dictionary<``int``, ``int``>();`   `        ``for` `(``int` `i = 0; i < N; i++)` `        ``{` `            ``for` `(``int` `j = i + 1; j < N; j++)` `            ``{` `                ``// Finding the third element ` `                ``int` `temp = arr[i] ^ arr[j] ^ K;` `                ``// If the third element is present in the dictionary, increment the cnt` `                ``if` `(mp.ContainsKey(temp))` `                    ``cnt += mp[temp];` `            ``}`   `            ``// Increase the frequency of the element in the dictionary` `            ``if` `(mp.ContainsKey(arr[i]))` `                ``mp[arr[i]]++;` `            ``else` `                ``mp[arr[i]] = 1;` `        ``}`   `        ``return` `cnt;` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `Main(``string``[] args)` `    ``{` `        ``int` `N = 6;` `        ``int``[] arr = { 2, 1, 3, 7, 5, 4 };` `        ``int` `K = 5;`   `        ``Console.WriteLine(CountTriplets(arr, N, K));` `    ``}` `}`   `// by phasing17`

## Javascript

 `// Function for counting triplets` `function` `count_triplets(arr, N, K) {`   `    ``// cnt variable to count the triplets` `    ``let cnt = 0;` `    `  `    ``// map for storing the frequency of elements of the array    ` `    ``let mp = {};` `    ``for` `(let i = 0; i < N; i++) {` `        ``for` `(let j = i + 1; j < N; j++) {` `        `  `            ``// Finding the third element  ` `            ``let temp = arr[i] ^ arr[j] ^ K;` `            `  `            ``// If third element is present in the map, increment the cnt` `            ``if` `(temp ``in` `mp) {` `                ``cnt += mp[temp];` `            ``}` `        ``}` `        `  `        ``// increase the frequency of element in the map` `        ``mp[arr[i]] = (mp[arr[i]] || 0) + 1;` `    ``}` `    ``return` `cnt;` `}`   `// Driver code` `let N = 6;` `let arr = [2, 1, 3, 7, 5, 4];` `let K = 5;` `console.log(count_triplets(arr, N, K));`

Output

```2

```

Time Complexity: O(N2) ( if we use map instead of unordered map then the time complexity will be O(N2 * logN)).
Auxiliary Space: O(N)

Efficient Approach 2: The problem can be efficiently solved by using sorting, binary search and xor properties based on the following idea:

Sort the array and then run two nested loops to select two elements of the possible triplet. Use binary search to find if the third element is present or not with the help of Xor property (if a ^ x = K then a ^ K = x). If found, then there is possible triplet.

Follow the steps below to implement the idea:

• Sort the given array in non-decreasing order.
• Make a for loop which will point towards the first number of triplets.
• Make nested for loop which will point towards the second number of a triplet
• Third number will be: third_ele = X ^ arr[ i ] ^ arr[ j ], because  if a^b^c = d then c = d^a^b (xor property).
• Do a binary search in [ j+1, N-1 ]. If third_ele is present in this range, increase the count by 1.
• Finally return the count.

Below is the implementation of the above approach:

## C++

 `// C++ code to implement the approach`   `#include ` `using` `namespace` `std;`   `// Function to count all valid triplets` `int` `count_triplets(``int` `arr[], ``int` `N, ``int` `K)` `{` `    ``// Sort array to perform lower_bound` `    ``sort(arr, arr + N);` `    ``int` `cnt = 0;`   `    ``// Fixed arr[i] as a first element` `    ``for` `(``int` `i = 0; i < N; i++) {`   `        ``// Fixed arr[j] as a second element` `        ``for` `(``int` `j = i + 1; j < N; j++) {` `            ``int` `third_ele = K ^ arr[i] ^ arr[j];`   `            ``// Find third element` `            ``auto` `it = lower_bound(arr + j + 1,` `                                  ``arr + N, third_ele)` `                      ``- arr;` `            ``// If third element is present` `            ``// then increase cnt by 1` `            ``if` `(it != N && arr[it] == third_ele)` `                ``cnt++;` `        ``}` `    ``}`   `    ``return` `cnt;` `}`   `// Driver code` `int` `main()` `{` `    ``int` `N = 6;` `    ``int` `arr[] = { 2, 1, 3, 7, 5, 4 };` `    ``int` `K = 5;`   `    ``// Function call` `    ``cout << count_triplets(arr, N, K);` `    ``return` `0;` `}`

## Java

 `// Java code to implement the approach` `import` `java.io.*;` `import` `java.util.*;`   `class` `GFG ` `{`   `  ``// Function to find lower bound using binary search` `  ``public` `static` `int` `lower_bound(``int` `a[], ``int` `x, ``int` `l)` `  ``{`   `    ``// x is the target value or key` `    ``int` `r = a.length;` `    ``while` `(l + ``1` `< r) {` `      ``int` `m = (l + r) >>> ``1``;` `      ``if` `(a[m] >= x)` `        ``r = m;` `      ``else` `        ``l = m;` `    ``}` `    ``return` `r;` `  ``}` `  ``// Function to count all valid triplets` `  ``public` `static` `int` `count_triplets(``int` `arr[], ``int` `N,` `                                   ``int` `K)` `  ``{` `    ``// Sort array to perform lower_bound` `    ``Arrays.sort(arr);` `    ``int` `cnt = ``0``;`   `    ``// Fixed arr[i] as a first element` `    ``for` `(``int` `i = ``0``; i < N; i++) {`   `      ``// Fixed arr[j] as a second element` `      ``for` `(``int` `j = i + ``1``; j < N; j++) {` `        ``int` `third_ele = K ^ arr[i] ^ arr[j];`   `        ``// Find third element` `        ``int` `it = lower_bound(arr, third_ele, j);`   `        ``// If third element is present` `        ``// then increase cnt by 1` `        ``if` `(it != N && arr[it] == third_ele)` `          ``cnt++;` `      ``}` `    ``}`   `    ``return` `cnt;` `  ``}`   `  ``// Driver code` `  ``public` `static` `void` `main(String[] args)` `  ``{` `    ``int` `N = ``6``;` `    ``int` `arr[] = { ``2``, ``1``, ``3``, ``7``, ``5``, ``4` `};` `    ``int` `K = ``5``;`   `    ``// Function call` `    ``System.out.print(count_triplets(arr, N, K));` `  ``}` `}`   `// This code is contributed by Rohit Pradhan`

## Python3

 `# Python3 code for the above approach`   `# Function to find lower bound using binary search` `def` `lower_bound(a, x, l):` `  `  `    ``# x is the target value or key` `    ``r ``=` `len``(a)` `    ``while` `(l ``+` `1` `< r):` `        ``m ``=` `(l ``+` `r) >> ``1` `        ``if` `a[m] >``=` `x:` `            ``r ``=` `m ` `        ``else``:` `            ``l ``=` `m` `    ``return` `r`   `# Function to count all valid triplets` `def` `count_triplets(arr, N, K):` `  `  `    ``# sort array to perform lower_bound` `    ``arr.sort()` `    ``cnt ``=` `0` `    `  `    ``# Fixed arr[i] as a first element` `    ``for` `i ``in` `range``(N):` `      `  `        ``# Fixed arr[j] as a second element` `        ``for` `j ``in` `range``(i ``+` `1``, N):` `            ``third_ele ``=` `K ^ arr[i] ^ arr[j]` `            `  `            ``# Find third element` `            ``it ``=` `lower_bound(arr, third_ele, j)` `            `  `            ``# If third element is present` `            ``# then increase cnt by 1` `            ``if` `it !``=` `N ``and` `arr[it] ``=``=` `third_ele:` `                ``cnt ``+``=` `1` `    ``return` `cnt`   `# Driver Code` `N ``=` `6` `arr ``=` `[ ``2``, ``1``, ``3``, ``7``, ``5``, ``4` `]` `K ``=` `5`   `# Function call` `print``(count_triplets(arr, N, K))`   `# this code is contributed by phasing17`

## C#

 `// C# program for above approach` `using` `System;` `class` `GFG` `{`   `  ``// Function to find lower bound using binary search` `  ``public` `static` `int` `lower_bound(``int``[] a, ``int` `x, ``int` `l)` `  ``{`   `    ``// x is the target value or key` `    ``int` `r = a.Length;` `    ``while` `(l + 1 < r) {` `      ``int` `m = (l + r) >> 1;` `      ``if` `(a[m] >= x)` `        ``r = m;` `      ``else` `        ``l = m;` `    ``}` `    ``return` `r;` `  ``}` `  ``// Function to count all valid triplets` `  ``public` `static` `int` `count_triplets(``int``[] arr, ``int` `N,` `                                   ``int` `K)` `  ``{` `    ``// Sort array to perform lower_bound` `    ``Array.Sort(arr);` `    ``int` `cnt = 0;`   `    ``// Fixed arr[i] as a first element` `    ``for` `(``int` `i = 0; i < N; i++) {`   `      ``// Fixed arr[j] as a second element` `      ``for` `(``int` `j = i + 1; j < N; j++) {` `        ``int` `third_ele = K ^ arr[i] ^ arr[j];`   `        ``// Find third element` `        ``int` `it = lower_bound(arr, third_ele, j);`   `        ``// If third element is present` `        ``// then increase cnt by 1` `        ``if` `(it != N && arr[it] == third_ele)` `          ``cnt++;` `      ``}` `    ``}`   `    ``return` `cnt;` `  ``}`   `// Driver Code` `public` `static` `void` `Main()` `{` `    ``int` `N = 6;` `    ``int``[] arr = { 2, 1, 3, 7, 5, 4 };` `    ``int` `K = 5;`   `    ``// Function call` `    ``Console.Write(count_triplets(arr, N, K));` `}` `}`   `// This code is contributed by code_hunt.`

## Javascript

 ``

Output

```2

```

Time Complexity: O(N2 * logN)
Auxiliary Space: O(1)

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Previous
Next