Remove minimum number of elements such that no common element exist in both array | To find no elements to remove so no common element exist ; To store count of array element ; Count elements of a ; Count elements of b ; Traverse through all common element , and pick minimum occurrence from two arrays ; To return count of minimum elements ; Driver program to test above function
function minRemove ( a , b , n , m ) { let countA = new Map ( ) ; let countB = new Map ( ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( countA . has ( a [ i ] ) ) countA . set ( a [ i ] , countA . get ( a [ i ] ) + 1 ) ; else countA . set ( a [ i ] , 1 ) ; } for ( let i = 0 ; i < m ; i ++ ) { if ( countB . has ( b [ i ] ) ) countB . set ( b [ i ] , countB . get ( b [ i ] ) + 1 ) ; else countB . set ( b [ i ] , 1 ) ; } let res = 0 ; for ( let x of countA . keys ( ) ) if ( countB . has ( x ) ) res += Math . min ( countB . get ( x ) , countA . get ( x ) ) ; return res ; } let a = [ 1 , 2 , 3 , 4 ] ; let b = [ 2 , 3 , 4 , 5 , 8 ] ; let n = a . length ; let m = b . length ; document . write ( minRemove ( a , b , n , m ) ) ;