Check if elements of an array can be arranged satisfying the given condition | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; string canReorder ( int A [ ] , int n ) { map < int , int > m ; for ( int i = 0 ; i < n ; i ++ ) m [ A [ i ] ] ++ ; sort ( A , A + n ) ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( m [ A [ i ] ] == 0 ) continue ; if ( m [ 2 * A [ i ] ] ) { count += 2 ; m [ A [ i ] ] -= 1 ; m [ 2 * A [ i ] ] -= 1 ; } } if ( count == n ) return " true " ; else return " false " ; } int main ( ) { int A [ ] = { 4 , -2 , 2 , -4 } ; int n = sizeof ( A ) / sizeof ( int ) ; cout << ( canReorder ( A , n ) ) ; return 0 ; }