Partition an array into two subsets with equal count of unique elements | Function to partition the array into two subsets such that count of unique elements in both subsets is the same ; Stores the subset number for each array elements ; Stores the count of unique array elements ; Stores the frequency of elements ; Traverse the array ; Count of elements having a frequency of 1 ; Check if there exists any element with frequency > 2 ; Count of elements needed to have frequency exactly 1 in each subset ; Initialize all values in the / array ans [ ] as 1 ; Traverse the array ans [ ] ; This array element is a part of first subset ; Half array elements with frequency 1 are part of the second subset ; If count of elements is exactly 1 are odd and has no element with frequency > 2 ; If count of elements that occurs exactly once are even ; Print the result ; If the count of elements has exactly 1 frequency are odd and there is an element with frequency greater than 2 ; Print the result ; Driver Codea
function arrayPartition ( a , n ) { let ans = new Array ( n ) ; let cnt = 0 ; let ind , flag = 0 ; let mp = new Map ( ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( mp . has ( a [ i ] ) ) { mp . set ( a [ i ] , mp . get ( a [ i ] ) + 1 ) } else { mp . set ( a [ i ] , 1 ) } } for ( let i = 0 ; i < n ; i ++ ) { if ( mp . get ( a [ i ] ) == 1 ) cnt ++ ; if ( mp . get ( a [ i ] ) > 2 && flag == 0 ) { flag = 1 ; ind = i ; } } let p = Math . floor ( ( cnt + 1 ) / 2 ) ; let ans1 = 0 ; for ( let i = 0 ; i < n ; i ++ ) ans [ i ] = 1 ; for ( let i = 0 ; i < n ; i ++ ) { if ( mp . get ( a [ i ] ) == 1 && ans1 < p ) { ans [ i ] = 1 ; ans1 ++ ; } else if ( mp . get ( a [ i ] ) == 1 ) { ans [ i ] = 2 ; } } if ( cnt % 2 == 1 && flag == 0 ) { document . write ( - 1 + " " ) ; return ; } if ( cnt % 2 == 0 ) { for ( let i = 0 ; i < n ; i ++ ) { document . write ( ans [ i ] + " " ) ; } } else { for ( let i = 0 ; i < n ; i ++ ) { if ( ind == i ) document . write ( 2 + " " ) ; else document . write ( ans [ i ] << " " ) ; } } } let arr = [ 1 , 1 , 2 , 3 , 4 , 4 ] ; let N = arr . length arrayPartition ( arr , N ) ;