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
def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT def findArrangement ( arr , n ) : NEW_LINE INDENT if ( n < 2 ) : NEW_LINE INDENT print ( " - 1" , end = " " ) ; NEW_LINE return ; NEW_LINE DEDENT minVal = min ( arr ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == minVal ) : NEW_LINE INDENT arr [ i ] , arr [ n - 1 ] = arr [ n - 1 ] , arr [ i ] ; NEW_LINE break ; NEW_LINE DEDENT DEDENT andVal = arr [ 0 ] ; NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT andVal &= arr [ i ] ; NEW_LINE DEDENT if ( andVal == arr [ n - 1 ] ) : NEW_LINE INDENT printArr ( arr , n ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 5 , 3 , 3 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE findArrangement ( arr , n ) ; NEW_LINE DEDENT