Rearrange array elements such that Bitwise AND of first N | 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
function printArr ( arr , n ) { for ( var i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ; } function findArrangement ( arr , n ) { if ( n < 2 ) { document . write ( " " ) ; return ; } var minVal = arr . reduce ( ( a , b ) => Math . min ( a , b ) ) ; for ( var i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == minVal ) { [ arr [ i ] , arr [ n - 1 ] ] = [ arr [ n - 1 ] , arr [ i ] ] ; break ; } } var andVal = arr [ 0 ] ; for ( var i = 1 ; i < n - 1 ; i ++ ) { andVal &= arr [ i ] ; } if ( andVal == arr [ n - 1 ] ) printArr ( arr , n ) ; else document . write ( " " ) ; } var arr = [ 1 , 5 , 3 , 3 ] ; var n = arr . length ; findArrangement ( arr , n ) ;