Check if elements of an array can be arranged satisfying the given condition | Python implementation of the approach ; Function to return true if the elements can be arranged in the desired order ; If 2 * x is not found to pair ; Remove an occurrence of x and an occurrence of 2 * x ; Driver Code ; Function call to print required answer
import collections NEW_LINE def canReorder ( A ) : NEW_LINE INDENT count = collections . Counter ( A ) NEW_LINE for x in sorted ( A , key = abs ) : NEW_LINE INDENT if count [ x ] == 0 : NEW_LINE INDENT continue NEW_LINE DEDENT if count [ 2 * x ] == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT count [ x ] -= 1 NEW_LINE count [ 2 * x ] -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT A = [ 4 , - 2 , 2 , - 4 ] NEW_LINE print ( canReorder ( A ) ) NEW_LINE