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.
Be aware: 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 doable 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 downside will be solved primarily based 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 based on 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 a brilliant masks of b1 for all i from 2 to n − 1.
Observe 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 rely 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++
|
Time Complexity: O(N)
Auxiliary Area: O(1)
Associated Articles: