Rearrange array elements such that Bitwise AND of first N | C ++ implementation of the approach ; Utility function to print the elements of an array ; Function to find the required arrangement ; There has to be atleast 2 elements ; Minimum element from the array ; Swap any occurrence of the minimum element with the last element ; Find the bitwise AND of the first ( n - 1 ) elements ; If the bitwise AND is equal to the last element then print the arrangement ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } void findArrangement ( int arr [ ] , int n ) { if ( n < 2 ) { cout << " - 1" ; return ; } int minVal = * min_element ( arr , arr + n ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == minVal ) { swap ( arr [ i ] , arr [ n - 1 ] ) ; break ; } } int andVal = arr [ 0 ] ; for ( int i = 1 ; i < n - 1 ; i ++ ) { andVal &= arr [ i ] ; } if ( andVal == arr [ n - 1 ] ) printArr ( arr , n ) ; else cout << " - 1" ; } int main ( ) { int arr [ ] = { 1 , 5 , 3 , 3 } ; int n = sizeof ( arr ) / sizeof ( int ) ; findArrangement ( arr , n ) ; return 0 ; }