Given an array arr[] of measurement N, Return the variety of permutations of array arr[] which fulfill the situation arr[1] & arr[2] & . . . & arr[i] = arr[i+1] & arr[i+2] & . . . & arr[N] , for all i.
Notice: Right here & denotes the bitwise AND operation.
Examples:
Enter: N = 3, arr[] = { 1, 1, 1 }
Output: 6
Clarification: Since all of the numbers are equal, no matter permutation we take, the sequence will observe the above situation. There are a complete of 6 permutations attainable with index numbers from 1 to three : [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1].Enter: N = 4, arr[] = { 1, 3, 5, 1 }
Output: 4
Strategy: This drawback will be solved based mostly on the next concept:
Take into account an arbitrary sequence b1, b2, . . ., bn. First, allow us to outline the arrays AND_pref and AND_suf of size N the place
- AND_prefi = b1 & b2 & . . . & bi and
- AND_sufi = bi & bi+1 & . . . & bn.
In keeping with the definition of the sequence: AND_pref1 = AND_suf2. Now AND_pref2 ≤ AND_pref1 = AND_suf2 ≤ AND_suf3. Additionally in line with the definition, AND_pref2 = AND_suf3. Which means b1 = AND_pref2 = AND_suf3.
Equally, for all i from 1 to n, we get AND_prefi = b1 and AND_sufi = b1.
Due to this fact for the sequence, b1 = bn and the bi should be an excellent masks of b1 for all i from 2 to n − 1.
Comply with the steps beneath to unravel the issue:
- Initialize a variable preAnd with ( 1 << 30 ) – 1.
- Run a loop from i = 0 to n-1 and replace preAnd with ( preAnd & arr[i] ).
- Initialize a depend variable (say cnt) with 0.
- Run a loop from i = 0 to n – 1
- If preAnd = arr[i], then Increment cnt by 1.
- Compute (cnt * ( cnt – 1 ) * (n – 2) !) % (1e9 + 7) and retailer it within the reply variable.
- Return the reply.
Beneath is the implementation of the above method:
C++
// C++ code to implement the above method
#embody <bits/stdc++.h>
utilizing namespace std;
#outline ll lengthy lengthy
// Given mod quantity .
ll mod = 1e9 + 7;
// Perform performing calculation
int countAndGood(int n, vector<int>& arr)
{
// Initializing preAnd .
int preAnd = (1 << 30) - 1;
// Precomputing the And of the array arr
for (int i = 0; i < n; i++) {
preAnd = (preAnd & arr[i]);
}
// Initializing cnt with 0
ll cnt = 0;
// Counting the whole quantity in arr which
// are equal to preAnd
for (int i = 0; i < n; i++) {
if (preAnd == arr[i])
cnt++;
}
// Discovering (cnt)P(cnt-2)
ll ans = (cnt * (cnt - 1)) % mod;
// Discovering (n-2)!
ll temp = 1;
for (ll i = 2; i <= n - 2; i++) {
temp = (temp * i) % mod;
}
// Multiplying temp and ans
ans = (ans * temp) % mod;
// Returning ans variable
return ans;
}
// Driver code
int principal()
{
int N = 4;
vector<int> arr = { 1, 3, 5, 1 };
// Perform name
cout << countAndGood(N, arr);
return 0;
}
Time Complexity: O(N)
Auxiliary House: O(1)
Associated Articles: