Open In App

Count triples with Bitwise AND equal to Zero

Improve
Improve
Like Article
Like
Save
Share
Report

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 & 2

Input: 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 Code
int main()
{
 
    // Input Array
    vector<int> A = { 2, 1, 3 };
 
    // Function Call
    cout << countTriplets(A);
 
    return 0;
}


Java




// Java program for the above approach
import 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 Code
public 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 Code
if __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 approach
using 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 Code
public 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 Array
var A = [2, 1, 3];
// Function Call
document.write( countTriplets(A));
 
</script>


  

Output: 

12

 

Time Complexity: O(max(M*N, N2)) where M is the maximum element present in the given array
Auxiliary Space: O(M)



Last Updated : 09 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads