Count all triplets from given Array whose bitwise XOR is equal to K
Last Updated :
16 Oct, 2023
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 <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
// 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
// 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
<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>
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++
// 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;
}
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<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));
}
}
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));
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 <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
// 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
<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>
Time Complexity: O(N2 * logN)
Auxiliary Space: O(1)
Similar Reads
Count pairs from given array with Bitwise OR equal to K
Given an array arr[] consisting of N positive integers and an integer K, the task is to count all pairs possible from the given array with Bitwise OR equal to K. Examples: Input: arr[] = {2, 38, 44, 29, 62}, K = 46Output: 2Explanation: Only the following two pairs are present in the array whose Bitw
5 min read
Find bitwise XOR of all triplets formed from given three Arrays
Given three arrays arr1[], arr2[], and arr3[] consisting of non-negative integers. The task is to find the bitwise XOR of the XOR of all possible triplets that are formed by taking one element from each array. Examples: Input: arr1[] = {2, 3, 1}, arr2[] = {2, 4}, arr3[] = {3, 5}Output: 0Explanation:
11 min read
Count pairs having Bitwise XOR less than K from given array
Given an array arr[]of size N and an integer K, the task is to count the number of pairs from the given array such that the Bitwise XOR of each pair is less than K. Examples: Input: arr = {1, 2, 3, 5} , K = 5 Output: 4 Explanation: Bitwise XOR of all possible pairs that satisfy the given conditions
15+ min read
Make all array elements equal by replacing triplets with their Bitwise XOR
Given an array arr[] of size N, the task is to find all the triplets (i, j, k) such that replacing the elements of the triplets with their Bitwise XOR values, i.e. replacing arr[i], arr[j], arr[k] with (arr[i] ^ arr[j] ^ arr[k]) makes all array elements equal. If more than one solution exists, print
10 min read
Count of pairs from Array with sum equal to twice their bitwise AND
Given an array arr[], the task is to count the pairs in the array with sum equal to twice their bitwise AND, i.e., [Tex]A + B = 2 * (A \& B) [/Tex]Examples: Input: arr[] = {1, 1, 3, 4, 4, 5, 7, 8} Output: 2 Explanation: Pairs with sum equal to twice their bitwise AND: {(1, 1), (4, 4)}Input: arr[
7 min read
Count pairs having bitwise XOR greater than K from a given array
Given an array arr[]of size N and an integer K, the task is to count the number of pairs from the given array such that the Bitwise XOR of each pair is greater than K. Examples: Input: arr = {1, 2, 3, 5} , K = 2 Output: 4 Explanation: Bitwise XOR of all possible pairs that satisfy the given conditio
15+ min read
Count pairs from a given range having equal Bitwise OR and XOR values
Given an integer N, the task is to find the count total number of pairs (P, Q) from the range 0 ⤠P, Q < 2N, such that P OR Q = P XOR Q. Since the count can be very large, print it to modulo 109 + 7. Examples: Input: N = 1Output: 3Explanation: The pairs (P, Q) satisfying P OR Q = P XOR Q are (0,
11 min read
Count values whose Bitwise OR with A is equal to B
Given two integers A and B, the task is to count possible values of X that satisfies the condition A | X = B. Note: | represents Bitwise OR operation. Examples: Input: A = 2, B = 3Output: 2Explanation: Since, 2 | 1 = 3 and 2 | 3 = 3. Therefore, the possible values of x are 1 and 3. Input: A = 5, B =
6 min read
Count triples with Bitwise AND equal to Zero
Given an array of integers A[] consisting of N integers, find the number of triples of indices (i, j, k) such that A[i] & A[j] & A[k] is 0(<0 ? i, j, k ? N and & denotes Bitwise AND operator. Examples: Input: A[]={2, 1, 3}Output: 12Explanation: The following i, j, k triples can be cho
7 min read
Count of possible pairs whose sum and bitwise XOR is given
Given two integers S and X representing the sum and bitwise XOR respectively of two integers, the task is to find the count of all such possible pairs such that their sum is equal to S and bitwise XOR is equal to X. Examples: Input: S = 9, X = 5Output: 4Explanation: (2, 7), (3, 6), (6, 3), (7, 2) co
9 min read