Smallest element repeated exactly ‘ k ’ times ( not limited to small range ) | C # program to find the smallest element with frequency exactly k . ; Map is used to store the count of elements present in the array ; Traverse the map and find minimum element with frequency k . ; Driver code
using System ; using System . Linq ; using System . Collections . Generic ; class GFG { public static int smallestKFreq ( int [ ] a , int n , int k ) { Dictionary < int , int > m = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) if ( m . ContainsKey ( a [ i ] ) ) { var v = m [ a [ i ] ] ; m . Remove ( a [ i ] ) ; m . Add ( a [ i ] , v + 1 ) ; } else m . Add ( a [ i ] , 1 ) ; int res = int . MaxValue ; HashSet < int > s = new HashSet < int > ( m . Keys . ToArray ( ) ) ; foreach ( int temp in s ) if ( m [ temp ] == k ) res = Math . Min ( res , temp ) ; return ( res != int . MaxValue ) ? res : - 1 ; } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , 2 , 1 , 3 , 1 } ; int k = 2 ; Console . WriteLine ( smallestKFreq ( arr , arr . Length , k ) ) ; } }