Given an array of N integers. Find the number of subsequences of the given sequence such that for each subsequence it’s bitwise AND, OR and XOR values are all same. As answer can be very large so will calculate the answer modulo \(10^{9} + 7\) .
Examples :
Input : N = 4
2 2 3 2
Output : 5
All valid subsequences are [2, 2, 2], [2], [2], [2], [3].
Input : N = 2
1 1
Output : 2
All valid subsequences are [1], [1].
Approach :
- AND is a non-increasing function and OR is a non-decreasing function. So for a subsequence, if it’s bitwise AND and OR value is the same then all elements should be same. And meanwhile, we have to equal XOR value with these two values, so all elements in the subsequence should be same and length of this should be odd, otherwise, XOR will be 0. There is one edge case, that if all value of the subsequence is 0 then we can take it any number of times.
- So we will count the frequencies of each element in the array and count the number of possible subsequences.
- So if frequency of an element is x, the number of subsequences will be \({x}\choose{1}\) + \({x}\choose{3}\) + \({x}\choose{5}\) + …., which is equal to \(2^{(x – 1)}\) . For ‘0’ it will be \(2^{x}-1\) (if present).
- To calculate \(2^p\) , here we will use Fast Exponentiation.
Implementation :
#include<bits/stdc++.h>
using namespace std;
long power(long x, long y, long p) {
long res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
if (x == 0) return 0; // In case x is divisible by p;
while (y > 0) {
// If y is odd, multiply x with result
if (y & 1)
res = (res*x) % p;
// y must be even now
y = y>>1; // y = y/2
x = (x*x) % p;
}
return res;
}
//C++ implementation of above approach
long CountSubsequences(int a[], int n){
long M = 1000000007;
map<int, int>freq; //store frequency of each elements
for(long i = 0; i < n; i++){
freq[a[i]]++;
}
long ans = 0; //stores the answer
for(auto i : freq){
if(i.first == 0){
//if the element is '0' the we can take any subset
//except the empty subset.
ans = (ans + (power(2, i.second, M) - 1 + M)) % M;;
}else{
//only odd length subsequence is valid
ans = (ans + power(2, i.second - 1, M)) % M;
}
}
return ans;
}
//Driver Code
int main(){
int arr[] = {1, 0, 0, 4, 4, 4, 1, 3};
int n = sizeof(arr) / sizeof(arr[0]);
long ans = CountSubsequences(arr, n);
cout << ans << "\n";
return 0;
}
Output : 10
Time Complexity : O(N * logN)