Number of subsets with same AND, OR and XOR values in an Array

Given an array arr[] of size N consisting of non-negative integers, the task is to find the number of non-empty subsets of the array such that the bitwise AND, bitwise OR and bitwise XOR values of the subsequence are equal to each other.

Note: Since the answer can be large, mod it with 1000000007.

Examples:

Input: arr[] = [1, 3, 2, 1, 2, 1]
Output: 7
Explanation:
One of the subsequences with equal bitwise Xor, bitwise or and bitwise AND is {1, 1, 1}.

Input: arr = [2, 3, 4, 5]
Output: 4



Naive Approach The naive approach for this problem is to traverse through all the subsets of the array in an iterative manner, and for each subset find the bitwise AND, OR and XOR value and check whether they are equal or not. Finally, return the count of such equal subsets.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to find the number
// of subsets with equal bitwise AND,
// OR and XOR values
  
#include <bits/stdc++.h>
using namespace std;
const int mod = 1000000007;
  
// Function to find the number of
// subsets with equal bitwise AND,
// OR and XOR values
int countSubsets(int a[], int n)
{
    int answer = 0;
  
    // Traverse through all the subsets
    for (int i = 0; i < (1 << n); i++) {
  
        int bitwiseAND = -1;
        int bitwiseOR = 0;
        int bitwiseXOR = 0;
  
        // Finding the subsets with the bits
        // of 'i' which are set
        for (int j = 0; j < n; j++) {
  
            // Computing the bitwise AND
            if (i & (1 << j)) {
                if (bitwiseAND == -1)
                    bitwiseAND = a[j];
                else
                    bitwiseAND &= a[j];
  
                // Computing the bitwise OR
                bitwiseOR |= a[j];
  
                // Computing the bitwise XOR
                bitwiseXOR ^= a[j];
            }
        }
  
        // Comparing all the three values
        if (bitwiseAND == bitwiseOR
            && bitwiseOR == bitwiseXOR)
            answer = (answer + 1) % mod;
    }
    return answer;
}
  
// Driver code
int main()
{
    int N = 6;
    int A[N] = { 1, 3, 2, 1, 2, 1 };
  
    cout << countSubsets(A, N);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation to find the number
// of subsets with equal bitwise AND,
// OR and XOR values
import java.io.*;
  
class GFG {
static int mod = 1000000007;
  
// Function to find the number of
// subsets with equal bitwise AND,
// OR and XOR values
static int countSubsets(int a[], int n)
{
    int answer = 0;
  
    // Traverse through all the subsets
    for (int i = 0; i < (1 << n); i++) {
  
        int bitwiseAND = -1;
        int bitwiseOR = 0;
        int bitwiseXOR = 0;
  
        // Finding the subsets with the bits
        // of 'i' which are set
        for (int j = 0; j < n; j++) {
  
            // Computing the bitwise AND
            if ((i & (1 << j)) == 0) {
                if (bitwiseAND == -1)
                    bitwiseAND = a[j];
                else
                    bitwiseAND &= a[j];
  
                // Computing the bitwise OR
                bitwiseOR |= a[j];
  
                // Computing the bitwise XOR
                bitwiseXOR ^= a[j];
            }
        }
  
        // Comparing all the three values
        if (bitwiseAND == bitwiseOR
            && bitwiseOR == bitwiseXOR)
            answer = (answer + 1) % mod;
    }
    return answer;
}
  
// Driver Code
public static void main (String[] args)
{
    int N = 6;
    int A[] = { 1, 3, 2, 1, 2, 1 };
  
    System.out.print(countSubsets(A, N));
}
}
  
// This code is contributed by shivanisinghss2110

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation to find the number 
# of subsets with equal bitwise AND, 
# OR and XOR values 
  
mod = 1000000007
  
# Function to find the number of 
# subsets with equal bitwise AND, 
# OR and XOR values 
def countSubsets(a, n) :
  
    answer = 0
  
    # Traverse through all the subsets 
    for i in range(1 << n) :
  
        bitwiseAND = -1
        bitwiseOR = 0
        bitwiseXOR = 0
  
        # Finding the subsets with the bits 
        # of 'i' which are set 
        for j in range(n) :
  
            # Computing the bitwise AND 
            if (i & (1 << j)) :
                if (bitwiseAND == -1) :
                    bitwiseAND = a[j]; 
                else :
                    bitwiseAND &= a[j]; 
  
                # Computing the bitwise OR 
                bitwiseOR |= a[j]; 
  
                # Computing the bitwise XOR 
                bitwiseXOR ^= a[j]; 
  
        # Comparing all the three values 
        if (bitwiseAND == bitwiseOR and bitwiseOR == bitwiseXOR) :
            answer = (answer + 1) % mod; 
      
    return answer; 
  
# Driver code 
if __name__ == "__main__"
      
    N = 6
    A = [ 1, 3, 2, 1, 2, 1 ]; 
  
    print(countSubsets(A, N)); 
  
# This code is contributed by AnkitRai01

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation to find the number
// of subsets with equal bitwise AND,
// OR and XOR values 
using System;
  
class GFG {
static int mod = 1000000007;
   
// Function to find the number of
// subsets with equal bitwise AND,
// OR and XOR values
static int countSubsets(int []a, int n)
{
    int answer = 0;
   
    // Traverse through all the subsets
    for (int i = 0; i < (1 << n); i++) {
   
        int bitwiseAND = -1;
        int bitwiseOR = 0;
        int bitwiseXOR = 0;
   
        // Finding the subsets with the bits
        // of 'i' which are set
        for (int j = 0; j < n; j++) {
   
            // Computing the bitwise AND
            if ((i & (1 << j)) == 0) {
                if (bitwiseAND == -1)
                    bitwiseAND = a[j];
                else
                    bitwiseAND &= a[j];
   
                // Computing the bitwise OR
                bitwiseOR |= a[j];
   
                // Computing the bitwise XOR
                bitwiseXOR ^= a[j];
            }
        }
   
        // Comparing all the three values
        if (bitwiseAND == bitwiseOR
            && bitwiseOR == bitwiseXOR)
            answer = (answer + 1) % mod;
    }
    return answer;
}
   
// Driver Code
public static void Main(String[] args)
{
    int N = 6;
    int []A = { 1, 3, 2, 1, 2, 1 };
   
    Console.Write(countSubsets(A, N));
}
}
  
// This code is contributed by 29AjayKumar

chevron_right


Output:

7

Time Complexity: O(N * 2N) where N is the size of the array.

Efficient Approach: The efficient approach lies behind the property of bitwise operations.

  • Using the property of bitwise AND, and bitwise OR we can say that if a & b == a | b, then a is equal to b. So if the AND and OR values of the subset are equal then all the elements of the subset are identical (say x). So the AND and OR values are equal to x.
  • Since all the values of subsequence are equal to each other, two case arise for XOR value:
    1. Subset size is odd: The XOR value equals to x.
    2. Subset size is even: The XOR values equals to 0.
  • Therefore, from the above observation, we can come to the conclusion that all odd-sized subsequences/subsets with equal elements follow the property.
  • In addition to this if all the elements of the subset are 0, then then the subset will follow the property (irrespective of subset size). So all the subsets which have only 0 as their element will be added to the answer.
  • If frequency of some element is K, the then number of odd sized subsets it can form is 2K – 1, and the total non-empty subsets it can form is 2K – 1.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find the number
// of subsets with equal bitwise
// AND, OR and XOR values
  
#include <bits/stdc++.h>
using namespace std;
const int mod = 1000000007;
  
// Function to find the number of
// subsets with equal bitwise AND,
// OR and XOR values
int countSubsets(int a[], int n)
{
    int answer = 0;
  
    // Precompute the modded powers
    // of two for subset counting
    int powerOfTwo[100005];
    powerOfTwo[0] = 1;
  
    // Loop to iterate and find the modded
    // powers of two for subset counting
    for (int i = 1; i < 100005; i++)
        powerOfTwo[i]
            = (powerOfTwo[i - 1] * 2)
              % mod;
  
    // Map to store the frequency of
    // each element
    unordered_map<int, int> frequency;
  
    // Loop to compute the frequency
    for (int i = 0; i < n; i++)
        frequency[a[i]]++;
  
    // For every element > 0, the number of
    // subsets formed using this element only
    // is equal to 2 ^ (frequency[element]-1).
    // And for 0, we have to find all
    // the subsets, so 2^(frequency[element]) -1
    for (auto el : frequency) {
  
        // If element is greater than 0
        if (el.first != 0)
            answer
                = (answer % mod
                   + powerOfTwo[el.second - 1])
                  % mod;
  
        else
            answer
                = (answer % mod
                   + powerOfTwo[el.second]
                   - 1 + mod)
                  % mod;
    }
    return answer;
}
  
// Driver code
int main()
{
    int N = 6;
    int A[N] = { 1, 3, 2, 1, 2, 1 };
  
    cout << countSubsets(A, N);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find the number
// of subsets with equal bitwise
// AND, OR and XOR values
   
  
import java.util.*;
  
class GFG{
static int mod = 1000000007;
   
// Function to find the number of
// subsets with equal bitwise AND,
// OR and XOR values
static int countSubsets(int a[], int n)
{
    int answer = 0;
   
    // Precompute the modded powers
    // of two for subset counting
    int []powerOfTwo = new int[100005];
    powerOfTwo[0] = 1;
   
    // Loop to iterate and find the modded
    // powers of two for subset counting
    for (int i = 1; i < 100005; i++)
        powerOfTwo[i]
            = (powerOfTwo[i - 1] * 2)
              % mod;
   
    // Map to store the frequency of
    // each element
    HashMap<Integer,Integer> frequency = new HashMap<Integer,Integer>();
   
    // Loop to compute the frequency
    for (int i = 0; i < n; i++)
        if(frequency.containsKey(a[i])){
            frequency.put(a[i], frequency.get(a[i])+1);
        }else{
            frequency.put(a[i], 1);
    }
   
    // For every element > 0, the number of
    // subsets formed using this element only
    // is equal to 2 ^ (frequency[element]-1).
    // And for 0, we have to find all
    // the subsets, so 2^(frequency[element]) -1
    for (Map.Entry<Integer,Integer> el : frequency.entrySet()) {
   
        // If element is greater than 0
        if (el.getKey() != 0)
            answer
                = (answer % mod
                   + powerOfTwo[el.getValue() - 1])
                  % mod;
   
        else
            answer
                = (answer % mod
                   + powerOfTwo[el.getValue()]
                   - 1 + mod)
                  % mod;
    }
    return answer;
}
   
// Driver code
public static void main(String[] args)
{
    int N = 6;
    int A[] = { 1, 3, 2, 1, 2, 1 };
   
    System.out.print(countSubsets(A, N));
   
}
}
  
// This code is contributed by 29AjayKumar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find the number
// of subsets with equal bitwise
// AND, OR and XOR values
using System;
using System.Collections.Generic;
  
class GFG{
      
static int mod = 1000000007;
  
// Function to find the number of
// subsets with equal bitwise AND,
// OR and XOR values
static int countSubsets(int []a, int n)
{
    int answer = 0;
  
    // Precompute the modded powers
    // of two for subset counting
    int []powerOfTwo = new int[100005];
    powerOfTwo[0] = 1;
  
    // Loop to iterate and find the modded
    // powers of two for subset counting
    for(int i = 1; i < 100005; i++)
       powerOfTwo[i] = (powerOfTwo[i - 1] * 2) % mod;
  
    // Map to store the frequency 
    // of each element
    Dictionary<int, int> frequency = new Dictionary<int, int>();
  
    // Loop to compute the frequency
    for(int i = 0; i < n; i++)
       if(frequency.ContainsKey(a[i]))
       {
           frequency[a[i]] = frequency[a[i]] + 1;
       }
       else
       {
           frequency.Add(a[i], 1);
       }
  
    // For every element > 0, the number of
    // subsets formed using this element only
    // is equal to 2 ^ (frequency[element]-1).
    // And for 0, we have to find all
    // the subsets, so 2^(frequency[element]) -1
    foreach (KeyValuePair<int, int> el in frequency)
    {
          
        // If element is greater than 0
        if (el.Key != 0)
            answer = (answer % mod + 
                      powerOfTwo[el.Value - 1]) % mod;
        else
            answer = (answer % mod + 
                      powerOfTwo[el.Value] - 1 +
                      mod) % mod;
    }
    return answer;
}
  
// Driver code
public static void Main(String[] args)
{
    int N = 6;
    int []A = { 1, 3, 2, 1, 2, 1 };
  
    Console.Write(countSubsets(A, N));
}
}
  
// This code is contributed by Rajput-Ji

chevron_right


Output:

7

Time Complexity: O(N), where N is the size of the array.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.