Remove minimum number of elements such that no common element exist in both array | C # Code to 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 code
using System ; using System . Collections . Generic ; class GFG { public static int minRemove ( int [ ] a , int [ ] b , int n , int m ) { Dictionary < int , int > countA = new Dictionary < int , int > ( ) ; Dictionary < int , int > countB = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( countA . ContainsKey ( a [ i ] ) ) { var v = countA [ a [ i ] ] ; countA . Remove ( countA [ a [ i ] ] ) ; countA . Add ( a [ i ] , v + 1 ) ; } else countA . Add ( a [ i ] , 1 ) ; } for ( int i = 0 ; i < m ; i ++ ) { if ( countB . ContainsKey ( b [ i ] ) ) { var v = countB [ b [ i ] ] ; countB . Remove ( countB [ b [ i ] ] ) ; countB . Add ( b [ i ] , v + 1 ) ; } else countB . Add ( b [ i ] , 1 ) ; } int res = 0 ; foreach ( int x in countA . Keys ) if ( countB . ContainsKey ( x ) ) res += Math . Min ( countB [ x ] , countA [ x ] ) ; return res ; } public static void Main ( String [ ] args ) { int [ ] a = { 1 , 2 , 3 , 4 } ; int [ ] b = { 2 , 3 , 4 , 5 , 8 } ; int n = a . Length ; int m = b . Length ; Console . WriteLine ( minRemove ( a , b , n , m ) ) ; } }