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++
#include <bits/stdc++.h>
using namespace std;
int count_triplets( int arr[], int N, int K)
{
int cnt = 0;
for ( int i = 0; i < N; i++) {
for ( int j = i + 1; j < N; j++) {
for ( int k = j + 1; k < N; k++) {
int triplet_xor = arr[i] ^ arr[j] ^ arr[k];
if (triplet_xor == K) {
cnt++;
}
}
}
}
return cnt;
}
int main()
{
int N = 6;
int arr[] = { 2, 1, 3, 7, 5, 4 };
int K = 5;
cout << count_triplets(arr, N, K);
return 0;
}
|
C
#include <stdio.h>
int count_triplets( int arr[], int N, int K)
{
int cnt = 0;
for ( int i = 0; i < N; i++) {
for ( int j = i + 1; j < N; j++) {
for ( int k = j + 1; k < N; k++) {
int triplet_xor
= arr[i] ^ arr[j] ^ arr[k];
if (triplet_xor == K) {
cnt++;
}
}
}
}
return cnt;
}
int main()
{
int N = 6;
int arr[] = { 2, 1, 3, 7, 5, 4 };
int K = 5;
printf ( "%d" , count_triplets(arr, N, K));
return 0;
}
|
Java
import java.util.*;
class FindTriplet {
int count_triplets( int arr[], int N, int K)
{
int cnt = 0 ;
for ( int i = 0 ; i < N; i++) {
for ( int j = i + 1 ; j < N; j++) {
for ( int k = j + 1 ; k < N;
k++) {
int triplet_xor
= arr[i] ^ arr[j]
^ arr[k];
if (triplet_xor == K) {
cnt++;
}
}
}
}
return cnt;
}
public static void main(String[] args)
{
FindTriplet triplet = new FindTriplet();
int N = 6 ;
int arr[] = { 2 , 1 , 3 , 7 , 5 , 4 };
int K = 5 ;
System.out.print(triplet.count_triplets(arr, N, K));
}
}
|
Python3
def count_triplets(arr, N, K):
cnt = 0
for i in range (N):
for j in range (i + 1 , N):
for k in range (j + 1 , N):
triplet_xor = arr[i] ^ arr[j] ^ arr[k]
if triplet_xor = = K:
cnt + = 1
return cnt
N = 6
arr = [ 2 , 1 , 3 , 7 , 5 , 4 ]
K = 5
print (count_triplets(arr, N, K))
|
C#
using System;
class GFG
{
static int count_triplets( int [] arr, int N, int K)
{
int cnt = 0;
for ( int i = 0; i < N; i++) {
for ( int j = i + 1; j < N; j++) {
for ( int k = j + 1; k < N; k++) {
int triplet_xor
= arr[i] ^ arr[j] ^ arr[k];
if (triplet_xor == K) {
cnt++;
}
}
}
}
return cnt;
}
public static int Main()
{
int N = 6;
int [] arr = new int [] { 2, 1, 3, 7, 5, 4 };
int K = 5;
Console.Write(count_triplets(arr, N, K));
return 0;
}
}
|
Javascript
<script>
const count_triplets = (arr, N, K) => {
let cnt = 0;
for (let i = 0; i < N; i++) {
for (let j = i + 1; j < N; j++) {
for (let k = j + 1; k < N; k++) {
let triplet_xor = arr[i] ^ arr[j] ^ arr[k];
if (triplet_xor == K) {
cnt++;
}
}
}
}
return cnt;
}
let N = 6;
let arr = [2, 1, 3, 7, 5, 4];
let K = 5;
document.write(count_triplets(arr, N, K));
</script>
|
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:
- It initializes a counter variable cnt to 0.
- It initializes an unordered map mp to store the frequency of each element in the array.
- It uses two nested loops to iterate through all possible pairs in the array.
- For each pair, it calculates the XOR of the two elements and the XOR required to get k (let’s say temp).
- If the required XOR value is present in the map, it increments the cnt variable by the frequency of the required XOR value.
- After iterating through all possible pairs, it increments the frequency of the current element in the map.
- After all possible pairs have been checked, the function returns the value of cnt.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int count_triplets( int arr[], int N, int K) {
int cnt = 0;
unordered_map< int , int > mp;
for ( int i = 0; i < N; i++) {
for ( int j = i + 1; j < N; j++) {
int temp = arr[i] ^ arr[j] ^ K;
if (mp.find(temp) != mp.end()) {
cnt += mp[temp];
}
}
mp[arr[i]]++;
}
return cnt;
}
int main() {
int N = 6;
int arr[] = {2, 1, 3, 7, 5, 4};
int K = 5;
cout << count_triplets(arr, N, K);
return 0;
}
|
Java
import java.util.HashMap;
public class GFG {
public static int count_triplets( int [] arr, int N, int K) {
int cnt = 0 ;
HashMap<Integer, Integer> mp = new HashMap<>();
for ( int i = 0 ; i < N; i++) {
for ( int j = i + 1 ; j < N; j++) {
int temp = arr[i] ^ arr[j] ^ K;
if (mp.containsKey(temp)) {
cnt += mp.get(temp);
}
}
if (mp.containsKey(arr[i])) {
mp.put(arr[i], mp.get(arr[i]) + 1 );
} else {
mp.put(arr[i], 1 );
}
}
return cnt;
}
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
def count_triplets(arr, N, K):
cnt = 0
mp = {}
for i in range (N):
for j in range (i + 1 , N):
temp = arr[i] ^ arr[j] ^ K
if temp in mp:
cnt + = mp[temp]
mp[arr[i]] = mp.get(arr[i], 0 ) + 1
return cnt
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
{
public static int CountTriplets( int [] arr, int N, int K)
{
int cnt = 0;
Dictionary< int , int > mp = new Dictionary< int , int >();
for ( int i = 0; i < N; i++)
{
for ( int j = i + 1; j < N; j++)
{
int temp = arr[i] ^ arr[j] ^ K;
if (mp.ContainsKey(temp))
cnt += mp[temp];
}
if (mp.ContainsKey(arr[i]))
mp[arr[i]]++;
else
mp[arr[i]] = 1;
}
return cnt;
}
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));
}
}
|
Javascript
function count_triplets(arr, N, K) {
let cnt = 0;
let mp = {};
for (let i = 0; i < N; i++) {
for (let j = i + 1; j < N; j++) {
let temp = arr[i] ^ arr[j] ^ K;
if (temp in mp) {
cnt += mp[temp];
}
}
mp[arr[i]] = (mp[arr[i]] || 0) + 1;
}
return cnt;
}
let N = 6;
let arr = [2, 1, 3, 7, 5, 4];
let K = 5;
console.log(count_triplets(arr, N, K));
|
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++
#include <bits/stdc++.h>
using namespace std;
int count_triplets( int arr[], int N, int K)
{
sort(arr, arr + N);
int cnt = 0;
for ( int i = 0; i < N; i++) {
for ( int j = i + 1; j < N; j++) {
int third_ele = K ^ arr[i] ^ arr[j];
auto it = lower_bound(arr + j + 1,
arr + N, third_ele)
- arr;
if (it != N && arr[it] == third_ele)
cnt++;
}
}
return cnt;
}
int main()
{
int N = 6;
int arr[] = { 2, 1, 3, 7, 5, 4 };
int K = 5;
cout << count_triplets(arr, N, K);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
public static int lower_bound( int a[], int x, int l)
{
int r = a.length;
while (l + 1 < r) {
int m = (l + r) >>> 1 ;
if (a[m] >= x)
r = m;
else
l = m;
}
return r;
}
public static int count_triplets( int arr[], int N,
int K)
{
Arrays.sort(arr);
int cnt = 0 ;
for ( int i = 0 ; i < N; i++) {
for ( int j = i + 1 ; j < N; j++) {
int third_ele = K ^ arr[i] ^ arr[j];
int it = lower_bound(arr, third_ele, j);
if (it != N && arr[it] == third_ele)
cnt++;
}
}
return cnt;
}
public static void main(String[] args)
{
int N = 6 ;
int arr[] = { 2 , 1 , 3 , 7 , 5 , 4 };
int K = 5 ;
System.out.print(count_triplets(arr, N, K));
}
}
|
Python3
def lower_bound(a, x, l):
r = len (a)
while (l + 1 < r):
m = (l + r) >> 1
if a[m] > = x:
r = m
else :
l = m
return r
def count_triplets(arr, N, K):
arr.sort()
cnt = 0
for i in range (N):
for j in range (i + 1 , N):
third_ele = K ^ arr[i] ^ arr[j]
it = lower_bound(arr, third_ele, j)
if it ! = N and arr[it] = = third_ele:
cnt + = 1
return cnt
N = 6
arr = [ 2 , 1 , 3 , 7 , 5 , 4 ]
K = 5
print (count_triplets(arr, N, K))
|
C#
using System;
class GFG
{
public static int lower_bound( int [] a, int x, int l)
{
int r = a.Length;
while (l + 1 < r) {
int m = (l + r) >> 1;
if (a[m] >= x)
r = m;
else
l = m;
}
return r;
}
public static int count_triplets( int [] arr, int N,
int K)
{
Array.Sort(arr);
int cnt = 0;
for ( int i = 0; i < N; i++) {
for ( int j = i + 1; j < N; j++) {
int third_ele = K ^ arr[i] ^ arr[j];
int it = lower_bound(arr, third_ele, j);
if (it != N && arr[it] == third_ele)
cnt++;
}
}
return cnt;
}
public static void Main()
{
int N = 6;
int [] arr = { 2, 1, 3, 7, 5, 4 };
int K = 5;
Console.Write(count_triplets(arr, N, K));
}
}
|
Javascript
<script>
function lower_bound(a, x, l)
{
let r = a.length;
while (l + 1 < r) {
let m = (l + r) >>> 1;
if (a[m] >= x)
r = m;
else
l = m;
}
return r;
}
function count_triplets(arr, N, K)
{
arr.sort();
let cnt = 0;
for (let i = 0; i < N; i++) {
for (let j = i + 1; j < N; j++) {
let third_ele = K ^ arr[i] ^ arr[j];
let it = lower_bound(arr, third_ele, j);
if (it != N && arr[it] == third_ele)
cnt++;
}
}
return cnt;
}
let N = 6;
let arr = [ 2, 1, 3, 7, 5, 4 ];
let K = 5;
document.write(count_triplets(arr, N, K));
</script>
|
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!
Last Updated :
16 Oct, 2023
Like Article
Save Article