Smallest subarray with all occurrences of a most frequent element | Python3 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
def smallestSubsegment ( a , n ) : NEW_LINE INDENT left = dict ( ) NEW_LINE count = dict ( ) NEW_LINE mx = 0 NEW_LINE mn , strindex = 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = a [ i ] NEW_LINE if ( x not in count . keys ( ) ) : NEW_LINE INDENT left [ x ] = i NEW_LINE count [ x ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT count [ x ] += 1 NEW_LINE DEDENT if ( count [ x ] > mx ) : NEW_LINE INDENT mx = count [ x ] NEW_LINE mn = i - left [ x ] + 1 NEW_LINE strindex = left [ x ] NEW_LINE DEDENT elif ( count [ x ] == mx and i - left [ x ] + 1 < mn ) : NEW_LINE INDENT mn = i - left [ x ] + 1 NEW_LINE strindex = left [ x ] NEW_LINE DEDENT DEDENT for i in range ( strindex , strindex + mn ) : NEW_LINE INDENT print ( a [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT A = [ 1 , 2 , 2 , 2 , 1 ] NEW_LINE n = len ( A ) NEW_LINE smallestSubsegment ( A , n ) NEW_LINE