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++ code to implement the above approach #include <bits/stdc++.h> 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 code to implement the approach #include <stdio.h> // 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 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 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# 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 |
<script> // JavaScript code to implement the above approach
// Count of all valid triplets
const count_triplets = (arr, N, K) => {
let cnt = 0;
// Fixed first element as arr[i]
for (let i = 0; i < N; i++) {
// Fixed second element as arr[j]
for (let j = i + 1; j < N; j++) {
// Now look for third element
for (let k = j + 1; k < N; k++) {
let 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
let N = 6;
let arr = [2, 1, 3, 7, 5, 4];
let K = 5;
// Function call
document.write(count_triplets(arr, N, K));
// This code is contributed by rakeshsahni </script> |
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:
- 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++ code for above approach #include <bits/stdc++.h> 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;
} |
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<Integer, Integer> 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));
}
} |
# 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))
|
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 |
// 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)); |
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.
-
Make nested for loop which will point towards the second number of a triplet
- Finally return the count.
Below is the implementation of the above approach:
// C++ code to implement the approach #include <bits/stdc++.h> 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 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 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# 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. |
<script> // JavaScript code for the above approach
// Function to find lower bound using binary search
function lower_bound(a, x, l)
{
// x is the target value or key
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 to count all valid triplets
function count_triplets(arr, N, K)
{
// Sort array to perform lower_bound
arr.sort();
let cnt = 0;
// Fixed arr[i] as a first element
for (let i = 0; i < N; i++) {
// Fixed arr[j] as a second element
for (let j = i + 1; j < N; j++) {
let third_ele = K ^ arr[i] ^ arr[j];
// Find third element
let 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
let N = 6;
let arr = [ 2, 1, 3, 7, 5, 4 ];
let K = 5;
// Function call
document.write(count_triplets(arr, N, K));
// This code is contributed by sanjoy_62. </script> |
2
Time Complexity: O(N2 * logN)
Auxiliary Space: O(1)