human
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"
Solution in Python:
assistant
#Here is code to smallest subarray with all occurrences of a most frequent element and the other steps required.
 def smallestSubsegment ( a , n ) :
	left = dict ( )
	count = dict ( )
	mx = 0
	mn , strindex = 0 , 0
	for i in range ( n ) :
		x = a [ i ]
		if ( x not in count . keys ( ) ) :
			left [ x ] = i
			count [ x ] = 1
		else :
			count [ x ] += 1
		if ( count [ x ] > mx ) :
			mx = count [ x ]
			mn = i - left [ x ] + 1
			strindex = left [ x ]
		elif ( count [ x ] == mx and i - left [ x ] + 1 < mn ) :
			mn = i - left [ x ] + 1
			strindex = left [ x ]
	for i in range ( strindex , strindex + mn ) :
		print ( a [ i ] , end = " ▁ " )
A = [ 1 , 2 , 2 , 2 , 1 ]
n = len ( A )
smallestSubsegment ( A , n )