
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Triples with Bitwise AND Equal to Zero in C++
Suppose we have an array of integers A. We have to find the number of triples of indices (i, j, k) such that −
0 <= i < size of A
0 <= j < size of A
0 <= k < size of A
A[i] AND A[j] AND A[k] is 0, where AND represents the bitwise-AND operator.
So, if the input is like [3,1,2], then the output will be 12
To solve this, we will follow these steps −
Define one map m
ret := 0
n := size of A
-
for initialize i := 0, when i < n, update (increase i by 1), do −
-
for initialize j := 0, when j < n, update (increase j by 1), do −
for initialize j := 0, when j < n, update (increase j by 1), do −
-
-
for initialize i := 0, when i < n, update (increase i by 1), do −
x := A[i]
-
for all key-value pairs a in m
-
if (a.key AND x) is same as 0, then −
ret := ret + a.value
-
return ret
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: int countTriplets(vector<int>& A){ unordered_map<int, int> m; int ret = 0; int n = A.size(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { m[A[i] & A[j]]++; } } for (int i = 0; i < n; i++) { int x = A[i]; for (auto& a : m) { if ((a.first & x) == 0) { ret += a.second; } } } return ret; } }; main(){ Solution ob; vector<int> v = {3,1,2}; cout << (ob.countTriplets(v)); }
Input
{3,1,2}
Output
12