Number of ordered pairs such that (Ai & Aj) = 0
Last Updated :
02 Feb, 2023
Given an array A[] of n integers, find out the number of ordered pairs such that Ai&Aj is zero, where 0<=(i,j)<n. Consider (i, j) and (j, i) to be different.
Constraints:
1<=n<=104
1<=Ai<=104
Examples:
Input : A[] = {3, 4, 2}
Output : 4
Explanation : The pairs are (3, 4) and (4, 2) which are
counted as 2 as (4, 3) and (2, 4) are considered different.
Input : A[]={5, 4, 1, 6}
Output : 4
Explanation : (4, 1), (1, 4), (6, 1) and (1, 6) are the pairs
Simple approach: A simple approach is to check for all possible pairs and count the number of ordered pairs whose bitwise & returns 0.
Below is the implementation of the above idea:
C++
// CPP program to calculate the number
// of ordered pairs such that their bitwise
// and is zero
#include <bits/stdc++.h>
using namespace std;
// Naive function to count the number
// of ordered pairs such that their
// bitwise and is 0
int countPairs(int a[], int n)
{
int count = 0;
// check for all possible pairs
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++)
if ((a[i] & a[j]) == 0)
// add 2 as (i, j) and (j, i) are
// considered different
count += 2;
}
return count;
}
// Driver Code
int main()
{
int a[] = { 3, 4, 2 };
int n = sizeof(a) / sizeof(a[0]);
cout << countPairs(a, n);
return 0;
}
Java
// Java program to calculate the number
// of ordered pairs such that their bitwise
// and is zero
class GFG {
// Naive function to count the number
// of ordered pairs such that their
// bitwise and is 0
static int countPairs(int a[], int n)
{
int count = 0;
// check for all possible pairs
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++)
if ((a[i] & a[j]) == 0)
// add 2 as (i, j) and (j, i) are
// considered different
count += 2;
}
return count;
}
// Driver Code
public static void main(String arg[])
{
int a[] = { 3, 4, 2 };
int n = a.length;
System.out.print(countPairs(a, n));
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python3 program to calculate the number
# of ordered pairs such that their
# bitwise and is zero
# Naive function to count the number
# of ordered pairs such that their
# bitwise and is 0
def countPairs(a, n):
count = 0
# check for all possible pairs
for i in range(0, n):
for j in range(i + 1, n):
if (a[i] & a[j]) == 0:
# add 2 as (i, j) and (j, i) are
# considered different
count += 2
return count
# Driver Code
a = [ 3, 4, 2 ]
n = len(a)
print (countPairs(a, n))
# This code is contributed
# by Shreyanshi Arun.
C#
// C# program to calculate the number
// of ordered pairs such that their
// bitwise and is zero
using System;
class GFG {
// Naive function to count the number
// of ordered pairs such that their
// bitwise and is 0
static int countPairs(int []a, int n)
{
int count = 0;
// check for all possible pairs
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
if ((a[i] & a[j]) == 0)
// add 2 as (i, j) and (j, i)
// arev considered different
count += 2;
}
return count;
}
// Driver Code
public static void Main()
{
int []a = { 3, 4, 2 };
int n = a.Length;
Console.Write(countPairs(a, n));
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to calculate the number
// of ordered pairs such that their
// bitwise and is zero
// Naive function to count the number
// of ordered pairs such that their
// bitwise and is 0
function countPairs($a, $n)
{
$count = 0;
// check for all possible pairs
for ($i = 0; $i < $n; $i++)
{
for ($j = $i + 1; $j < $n; $j++)
if (($a[$i] & $a[$j]) == 0)
// add 2 as (i, j) and (j, i) are
// considered different
$count += 2;
}
return $count;
}
// Driver Code
{
$a = array(3, 4, 2);
$n = sizeof($a) / sizeof($a[0]);
echo countPairs($a, $n);
return 0;
}
// This code is contributed by nitin mittal
JavaScript
<script>
// JavaScript program to calculate the number
// of ordered pairs such that their bitwise
// and is zero
// Naive function to count the number
// of ordered pairs such that their
// bitwise and is 0
const countPairs = (a, n) => {
let count = 0;
// check for all possible pairs
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++)
if ((a[i] & a[j]) == 0)
// add 2 as (i, j) and (j, i) are
// considered different
count += 2;
}
return count;
}
// Driver Code
let a = [3, 4, 2];
let n = a.length;
document.write(countPairs(a, n));
// This code is contributed by rakeshsahni
</script>
?>
Time Complexity: O(n2)
Auxiliary Space: O(1)
Efficient approach: An efficient approach is to use Sum over Subsets Dynamic Programming method and count the number of ordered pairs. In the SOS DP we find out the pairs whose bitwise & returned 0. Here we need to count the number of pairs.
Some key observations are the constraints, the maximum that an array element can be is 104. Calculating the mask up to (1<<15) will give us our answer. Use hashing to count the occurrence of every element. If the last bit is OFF, then relating to SOS dp, we will have a base case since there is only one possibility of OFF bit.
dp[mask][0] = freq(mask)
If the last bit is set ON, then we will have the base case as:
dp[mask][0] = freq(mask) + freq(mask^1)
We add freq(mask^1) to add the other possibility of OFF bit.
Iterate over N=15 bits, which is the maximum possible.
Let's consider the i-th bit to be 0, then no subset can differ from the mask in the i-th bit as it would mean that the numbers will have a 1 at i-th bit where the mask has a 0 which would mean that it is not a subset of the mask. Thus we conclude that the numbers now differ in the first (i-1) bits only. Hence,
DP(mask, i) = DP(mask, i-1)
Now the second case, if the i-th bit is 1, it can be divided into two non-intersecting sets. One containing numbers with i-th bit as 1 and differing from mask in the next (i-1) bits. Second containing numbers with ith bit as 0 and differing from mask
\oplus
(2i) in next (i-1) bits. Hence,
DP(mask, i) = DP(mask, i-1) + DP(mask
2i, i-1).
DP[mask][i] stores the number of subsets of mask which differ from mask only in first i bits. Iterate for all array elements, and for every array element add the number of subsets (dp[ ( ( 1<<N ) - 1 ) ^ a[i] ][ N ]) to the number of pairs. N = maximum number of bits.
Explanation of addition of dp[ ( ( 1<<N ) - 1 ) ^ a[i] ][N] to the number of pairs: Take an example of A[i] being 5, which is 101 in binary. For better understanding, assume N=3 in this case, therefore, the reverse of 101 will be 010 which on applying bitwise & gives 0. So (1<<3) gives 1000 which on subtraction from 1 gives 111. 111
\oplus
101 gives 010 which is the reversed bit.So dp[((1<<N)-1)^a[i]][N] will have the number of subsets that returns 0 on applying bitwise & operator.
Below is the implementation of the above idea:
C++
// CPP program to calculate the number
// of ordered pairs such that their bitwise
// and is zero
#include <bits/stdc++.h>
using namespace std;
const int N = 15;
// efficient function to count pairs
long long countPairs(int a[], int n)
{
// stores the frequency of each number
unordered_map<int, int> hash;
long long dp[1 << N][N + 1];
memset(dp, 0, sizeof(dp)); // initialize 0 to all
// count the frequency of every element
for (int i = 0; i < n; ++i)
hash[a[i]] += 1;
// iterate for all possible values that a[i] can be
for (long long mask = 0; mask < (1 << N); ++mask) {
// if the last bit is ON
if (mask & 1)
dp[mask][0] = hash[mask] + hash[mask ^ 1];
else // is the last bit is OFF
dp[mask][0] = hash[mask];
// iterate till n
for (int i = 1; i <= N; ++i) {
// if mask's ith bit is set
if (mask & (1 << i))
{
dp[mask][i] = dp[mask][i - 1] +
dp[mask ^ (1 << i)][i - 1];
}
else // if mask's ith bit is not set
dp[mask][i] = dp[mask][i - 1];
}
}
long long ans = 0;
// iterate for all the array element
// and count the number of pairs
for (int i = 0; i < n; i++)
ans += dp[((1 << N) - 1) ^ a[i]][N];
// return answer
return ans;
}
// Driver Code
int main()
{
int a[] = { 5, 4, 1, 6 };
int n = sizeof(a) / sizeof(a[0]);
cout << countPairs(a, n);
return 0;
}
Java
// Java program to calculate
// the number of ordered pairs
// such that their bitwise
// and is zero
import java.util.*;
class GFG{
static int N = 15;
// Efficient function to count pairs
public static int countPairs(int a[],
int n)
{
// Stores the frequency of
// each number
HashMap<Integer,
Integer> hash = new HashMap<>();
int dp[][] = new int[1 << N][N + 1];
// Initialize 0 to all
// Count the frequency
// of every element
for (int i = 0; i < n; ++i)
{
if(hash.containsKey(a[i]))
{
hash.replace(a[i],
hash.get(a[i]) + 1);
}
else
{
hash.put(a[i], 1);
}
}
// Iterate for all possible
// values that a[i] can be
for (int mask = 0;
mask < (1 << N); ++mask)
{
// If the last bit is ON
if ((mask & 1) != 0)
{
if(hash.containsKey(mask))
{
dp[mask][0] = hash.get(mask);
}
if(hash.containsKey(mask ^ 1))
{
dp[mask][0] += hash.get(mask ^ 1);
}
}
else
{
// is the last bit is OFF
if(hash.containsKey(mask))
{
dp[mask][0] = hash.get(mask);
}
}
// Iterate till n
for (int i = 1; i <= N; ++i)
{
// If mask's ith bit is set
if ((mask & (1 << i)) != 0)
{
dp[mask][i] = dp[mask][i - 1] +
dp[mask ^ (1 << i)][i - 1];
}
else
{
// If mask's ith bit is not set
dp[mask][i] = dp[mask][i - 1];
}
}
}
int ans = 0;
// Iterate for all the
// array element and
// count the number of pairs
for (int i = 0; i < n; i++)
{
ans += dp[((1 << N) - 1) ^ a[i]][N];
}
// return answer
return ans;
}
// Driver code
public static void main(String[] args)
{
int a[] = {5, 4, 1, 6};
int n = a.length;
System.out.print(countPairs(a, n));
}
}
// This code is contributed by divyeshrabadiya07
Python3
# Python program to calculate the number
# of ordered pairs such that their bitwise
# and is zero
N = 15
# efficient function to count pairs
def countPairs(a, n):
# stores the frequency of each number
Hash = {}
# initialize 0 to all
dp = [[0 for i in range(N + 1)] for j in range(1 << N)]
# count the frequency of every element
for i in range(n):
if a[i] not in Hash:
Hash[a[i]] = 1
else:
Hash[a[i]] += 1
# iterate for all possible values that a[i] can be
mask = 0
while(mask < (1 << N)):
if mask not in Hash:
Hash[mask] = 0
# if the last bit is ON
if(mask & 1):
dp[mask][0] = Hash[mask] + Hash[mask ^ 1]
else: # is the last bit is OFF
dp[mask][0] = Hash[mask]
# iterate till n
for i in range(1, N + 1):
# if mask's ith bit is set
if(mask & (1 << i)):
dp[mask][i] = dp[mask][i - 1] + dp[mask ^ (1 << i)][i - 1]
else: # if mask's ith bit is not set
dp[mask][i] = dp[mask][i - 1]
mask += 1
ans = 0
# iterate for all the array element
# and count the number of pairs
for i in range(n):
ans += dp[((1 << N) - 1) ^ a[i]][N]
# return answer
return ans
# Driver Code
a = [5, 4, 1, 6]
n = len(a)
print(countPairs(a, n))
# This code is contributed by avanitrachhadiya2155
C#
// C# program to calculate
// the number of ordered pairs
// such that their bitwise
// and is zero
using System;
using System.Collections.Generic;
class GFG {
static int N = 15;
// Efficient function to count pairs
static int countPairs(int[] a, int n)
{
// Stores the frequency of
// each number
Dictionary<int, int> hash = new Dictionary<int, int>();
int[, ] dp = new int[1 << N, N + 1];
// Initialize 0 to all
// Count the frequency
// of every element
for (int i = 0; i < n; ++i)
{
if(hash.ContainsKey(a[i]))
{
hash[a[i]] += 1;
}
else
{
hash.Add(a[i], 1);
}
}
// Iterate for all possible
// values that a[i] can be
for (int mask = 0;
mask < (1 << N); ++mask)
{
// If the last bit is ON
if ((mask & 1) != 0)
{
if(hash.ContainsKey(mask))
{
dp[mask, 0] = hash[mask];
}
if(hash.ContainsKey(mask ^ 1))
{
dp[mask, 0] += hash[mask ^ 1];
}
}
else
{
// is the last bit is OFF
if(hash.ContainsKey(mask))
{
dp[mask, 0] = hash[mask];
}
}
// Iterate till n
for (int i = 1; i <= N; ++i)
{
// If mask's ith bit is set
if ((mask & (1 << i)) != 0)
{
dp[mask, i] = dp[mask, i - 1] +
dp[mask ^ (1 << i), i - 1];
}
else
{
// If mask's ith bit is not set
dp[mask, i] = dp[mask, i - 1];
}
}
}
int ans = 0;
// Iterate for all the
// array element and
// count the number of pairs
for (int i = 0; i < n; i++)
{
ans += dp[((1 << N) - 1) ^ a[i], N];
}
// return answer
return ans;
}
// Driver code
static void Main()
{
int[] a = {5, 4, 1, 6};
int n = a.Length;
Console.WriteLine(countPairs(a, n));
}
}
// This code is contributed by divyesh072019
JavaScript
<script>
// JavaScript program to calculate the number
// of ordered pairs such that their bitwise
// and is zero
const N = 15;
// efficient function to count pairs
function countPairs(a, n)
{
// stores the frequency of each number
let hash = new Map();
let dp = new Array((1 << N));
for (let i = 0; i < (1 << N); i++) {
dp[i] = new Array(N+1).fill(0); // initialize 0 to all
}
// count the frequency of every element
for (let i = 0; i < n; ++i){
if(hash.has(a[i])){
hash.set(a[i], hash.get(a[i]) + 1);
}
else{
hash.set(a[i], 1);
}
}
// iterate for all possible values that a[i] can be
for (let mask = 0; mask < (1 << N); mask++) {
// console.log(mask);
// if the last bit is ON
if (mask & 1){
dp[mask][0] = ((hash.get(mask) != undefined) ? hash.get(mask): 0) + ((hash.get((mask ^ 1)) != undefined) ? hash.get((mask^1)): 0);
}
else{
// is the last bit is OFF
dp[mask][0] = hash.get(mask) != undefined ? hash.get(mask) : 0;
}
// iterate till n
for (let i = 1; i <= N; i++) {
// if mask's ith bit is set
if (mask & (1 << i)){
dp[mask][i] = dp[mask][i - 1] + dp[mask ^ (1 << i)][i - 1];
}
else{
// if mask's ith bit is not set
dp[mask][i] = dp[mask][i - 1];
}
}
}
let ans = 0;
// iterate for all the array element
// and count the number of pairs
for (let i = 0; i < n; i++){
ans = ans + dp[((1 << N) - 1) ^ a[i]][N];
}
// return answer
return ans;
}
// Driver Code
let a = [ 5, 4, 1, 6 ];
let n = a.length
document.write(countPairs(a, n));
// The code is contributed by Gautam goel
</script>
Time Complexity: O(N*2N) where N=15 which is a maximum number of bits possible, since Amax=104.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem