Least frequent element in an array | C # program to find the least frequent element in an array . ; Insert all elements in hash . ; find the min frequency ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static int leastFrequent ( int [ ] arr , int n ) { Dictionary < int , int > count = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int key = arr [ i ] ; if ( count . ContainsKey ( key ) ) { int freq = count [ key ] ; freq ++ ; count [ key ] = freq ; } else count . Add ( key , 1 ) ; } int min_count = n + 1 , res = - 1 ; foreach ( KeyValuePair < int , int > pair in count ) { if ( min_count >= pair . Value ) { res = pair . Key ; min_count = pair . Value ; } } return res ; } static void Main ( ) { int [ ] arr = new int [ ] { 1 , 3 , 2 , 1 , 2 , 2 , 3 , 1 } ; int n = arr . Length ; Console . Write ( leastFrequent ( arr , n ) ) ; } }