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: 12
Explanation: The following i, j, k triples can be chosen whose bitwise AND is zero:
(i=0, j=0, k=1) : 2 & 2 & 1
(i=0, j=1, k=0) : 2 & 1 & 2
(i=0, j=1, k=1) : 2 & 1 & 1
(i=0, j=1, k=2) : 2 & 1 & 3
(i=0, j=2, k=1) : 2 & 3 & 1
(i=1, j=0, k=0) : 1 & 2 & 2
(i=1, j=0, k=1) : 1 & 2 & 1
(i=1, j=0, k=2) : 1 & 2 & 3
(i=1, j=1, k=0) : 1 & 1 & 2
(i=1, j=2, k=0) : 1 & 3 & 2
(i=2, j=0, k=1) : 3 & 2 & 1
(i=2, j=1, k=0) : 3 & 1 & 2Input: A[]={21, 15, 6}
Output: 0
Explanation: No such triplets exist.
Approach: The idea to solve this problem is to use a Map to process the array solving elements. Follow the steps below to solve the problem:
- Initialize a Map to store frequencies of every possible value of A[i] & A[j]. Also, initialize a variable answer with 0, to store the required count.
- Traverse the array and for each array element, traverse the map and check for each map if key, if it’s Bitwise AND with the current array element is 0 or not. For every array element for which it is found to be true, increase answer by frequency of the key.
- After completing the traversal of the array, print answer.
Below is the implementation of the above approach:
C++
// C++ program for the above approachÂ
#include <bits/stdc++.h>#include <iostream>using namespace std;Â
// Function to find the number of// triplets whose Bitwise AND is 0.int countTriplets(vector<int>& A){    // Stores the count of triplets    // having bitwise AND equal to 0    int cnt = 0;Â
    // Stores frequencies of all possible A[i] & A[j]    unordered_map<int, int> tuples;Â
    // Traverse the array    for (auto a : A)Â
        // Update frequency of Bitwise AND        // of all array elements with a        for (auto b : A)            ++tuples[a & b];Â
    // Traverse the array    for (auto a : A)Â
        // Iterate the map        for (auto t : tuples)Â
            // If bitwise AND of triplet            // is zero, increment cnt            if ((t.first & a) == 0)                cnt += t.second;Â
    // Return the number of triplets    // whose Bitwise AND is 0.    return cnt;}Â
// Driver Codeint main(){Â
    // Input Array    vector<int> A = { 2, 1, 3 };Â
    // Function Call    cout << countTriplets(A);Â
    return 0;} |
Java
// Java program for the above approachimport java.util.*;class GFG{Â
// Function to find the number of// triplets whose Bitwise AND is 0.static int countTriplets(int []A){       // Stores the count of triplets    // having bitwise AND equal to 0    int cnt = 0;Â
    // Stores frequencies of all possible A[i] & A[j]    HashMap<Integer,Integer> tuples = new HashMap<Integer,Integer>();Â
    // Traverse the array    for (int a : A)Â
        // Update frequency of Bitwise AND        // of all array elements with a        for (int b : A)         {            if(tuples.containsKey(a & b))                tuples.put(a & b, tuples.get(a & b) + 1);            else                tuples.put(a & b, 1);        }Â
    // Traverse the array    for (int a : A)Â
        // Iterate the map        for (Map.Entry<Integer, Integer> t : tuples.entrySet())Â
            // If bitwise AND of triplet            // is zero, increment cnt            if ((t.getKey() & a) == 0)                cnt += t.getValue();Â
    // Return the number of triplets    // whose Bitwise AND is 0.    return cnt;}Â
// Driver Codepublic static void main(String[] args){Â
    // Input Array    int []A = { 2, 1, 3 };Â
    // Function Call    System.out.print(countTriplets(A));}}Â
// This code is contributed by shikhasingrajput |
Python3
# Python3 program for the above approachÂ
# Function to find the number of# triplets whose Bitwise AND is 0.def countTriplets(A) :Â
    # Stores the count of triplets    # having bitwise AND equal to 0    cnt = 0;Â
    # Stores frequencies of all possible A[i] & A[j]    tuples = {};Â
    # Traverse the array    for a in A:Â
        # Update frequency of Bitwise AND        # of all array elements with a        for b in A:            if (a & b) in tuples:                 tuples[a & b] += 1;                           else:                tuples[a & b] = 1;Â
    # Traverse the array    for a in A:                 # Iterate the map        for t in tuples: Â
            # If bitwise AND of triplet            # is zero, increment cnt            if ((t & a) == 0):                cnt += tuples[t];Â
    # Return the number of triplets    # whose Bitwise AND is 0.    return cnt;Â
# Driver Codeif __name__ ==Â "__main__" :Â
    # Input Array    A = [ 2, 1, 3 ];Â
    # Function Call    print(countTriplets(A));Â
    # This code is contributed by AnkThon |
C#
// C# program for the above approachusing System;using System.Collections.Generic;Â
class GFG{Â
// Function to find the number of// triplets whose Bitwise AND is 0.static int countTriplets(int []A){       // Stores the count of triplets    // having bitwise AND equal to 0    int cnt = 0;Â
    // Stores frequencies of all possible A[i] & A[j]    Dictionary<int,int> tuples = new Dictionary<int,int>();Â
    // Traverse the array    foreach (int a in A)Â
        // Update frequency of Bitwise AND        // of all array elements with a        foreach (int b in A)         {            if(tuples.ContainsKey(a & b))                tuples[a & b] = tuples[a & b] + 1;            else                tuples.Add(a & b, 1);        }Â
    // Traverse the array    foreach (int a in A)Â
        // Iterate the map        foreach (KeyValuePair<int, int> t in tuples)Â
            // If bitwise AND of triplet            // is zero, increment cnt            if ((t.Key & a) == 0)                cnt += t.Value;Â
    // Return the number of triplets    // whose Bitwise AND is 0.    return cnt;}Â
// Driver Codepublic static void Main(String[] args){Â
    // Input Array    int []A = { 2, 1, 3 };Â
    // Function Call    Console.Write(countTriplets(A));}}Â
// This code is contributed by 29AjayKumar |
Javascript
<script>Â
// Javascript program for the above approachÂ
// Function to find the number of// triplets whose Bitwise AND is 0.function countTriplets(A){    // Stores the count of triplets    // having bitwise AND equal to 0    var cnt = 0;Â
    // Stores frequencies of all possible A[i] & A[j]    var tuples = new Map();Â
    // Traverse the array    A.forEach(a => {                 // Update frequency of Bitwise AND        // of all array elements with a        A.forEach(b => {                         if(tuples.has(a & b))                tuples.set(a & b, tuples.get(a & b)+1)            else                tuples.set(a & b, 1)        });    });Â
    // Traverse the array    A.forEach(a => {                 // Update frequency of Bitwise AND        // of all array elements with a        tuples.forEach((value, key) => {                         // If bitwise AND of triplet            // is zero, increment cnt            if ((key & a) == 0)                cnt += value;        });    });     Â
    // Return the number of triplets    // whose Bitwise AND is 0.    return cnt;}Â
// Driver Code// Input Arrayvar A = [2, 1, 3];// Function Calldocument.write( countTriplets(A));Â
</script> |
 Â
12
Â
Time Complexity: O(max(M*N, N2)) where M is the maximum element present in the given array
Auxiliary Space: O(M)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!


