Check if elements of an array can be arranged satisfying the given condition | Java 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 java . util . HashMap ; import java . util . Map ; import java . util . Arrays ; class GfG { static String canReorder ( int A [ ] , int n ) { HashMap < Integer , Integer > m = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( m . containsKey ( A [ i ] ) ) m . put ( A [ i ] , m . get ( A [ i ] ) + 1 ) ; else m . put ( A [ i ] , 1 ) ; } Arrays . sort ( A ) ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( m . get ( A [ i ] ) == 0 ) continue ; if ( m . containsKey ( 2 * A [ i ] ) ) { count += 2 ; m . put ( A [ i ] , m . get ( A [ i ] ) - 1 ) ; m . put ( 2 * A [ i ] , m . get ( 2 * A [ i ] ) - 1 ) ; } } if ( count == n ) return " true " ; else return " false " ; } public static void main ( String [ ] args ) { int A [ ] = { 4 , - 2 , 2 , - 4 } ; int n = A . length ; System . out . println ( canReorder ( A , n ) ) ; } }