Smallest subarray with all occurrences of a most frequent element | C # implementation to find smallest subarray with all occurrences of a most frequent element ; To store left most occurrence of elements ; To store counts of elements ; To store maximum frequency ; To store length and starting index of smallest result window ; First occurrence of an element , store the index ; increase the frequency of elements ; Find maximum repeated element and store its last occurrence and first occurrence ; length of subsegment ; select subsegment of smallest size ; Print the subsegment with all occurrences of a most frequent element ; Driver code
using System ; using System . Collections . Generic ; class GfG { static void smallestSubsegment ( int [ ] a , int n ) { Dictionary < int , int > left = new Dictionary < int , int > ( ) ; Dictionary < int , int > count = new Dictionary < int , int > ( ) ; int mx = 0 ; int mn = - 1 , strindex = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { int x = a [ i ] ; if ( ! count . ContainsKey ( x ) ) { left . Add ( x , i ) ; count . Add ( x , 1 ) ; } else count [ x ] = count [ x ] + 1 ; if ( count [ x ] > mx ) { mx = count [ x ] ; mn = i - left [ x ] + 1 ; strindex = left [ x ] ; } else if ( ( count [ x ] == mx ) && ( i - left [ x ] + 1 < mn ) ) { mn = i - left [ x ] + 1 ; strindex = left [ x ] ; } } for ( int i = strindex ; i < strindex + mn ; i ++ ) Console . Write ( a [ i ] + " ▁ " ) ; } public static void Main ( String [ ] args ) { int [ ] A = { 1 , 2 , 2 , 2 , 1 } ; int n = A . Length ; smallestSubsegment ( A , n ) ; } }