# Depend permutations whose prefix & suffix AND are similar for every index

0
11

Given an array arr[] of measurement N, Return the variety of permutations of array arr[] which fulfill the situation arr & arr & . . . & 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:
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.
 ` `  `#embody ` `utilizing` `namespace` `std;` `#outline ll lengthy lengthy` ` `  `ll mod = 1e9 + 7;` ` `  `int` `countAndGood(``int` `n, vector<``int``>& arr)` `{` `    ` `    ``int` `preAnd = (1 << 30) - 1;` ` `  `    ` `    ``for` `(``int` `i = 0; i < n; i++) {` `        ``preAnd = (preAnd & arr[i]);` `    ``}` ` `  `    ` `    ``ll cnt = 0;` ` `  `    ` `    ` `    ``for` `(``int` `i = 0; i < n; i++) {` `        ``if` `(preAnd == arr[i])` `            ``cnt++;` `    ``}` ` `  `    ` `    ``ll ans = (cnt * (cnt - 1)) % mod;` ` `  `    ` `    ``ll temp = 1;` `    ``for` `(ll i = 2; i <= n - 2; i++) {` `        ``temp = (temp * i) % mod;` `    ``}` ` `  `    ` `    ``ans = (ans * temp) % mod;` ` `  `    ` `    ``return` `ans;` `}` ` `  `int` `most important()` `{` `    ``int` `N = 4;` `    ``vector<``int``> arr = { 1, 3, 5, 1 };` ` `  `    ` `    ``cout << countAndGood(N, arr);` ` `  `    ``return` `0;` `}`