Most frequent element in an array | Python3 program to find the most frequent element in an array . ; Sort the array ; find the max frequency using linear traversal ; If last element is most frequent ; Driver Code
def mostFrequent ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE max_count = 1 ; res = arr [ 0 ] ; curr_count = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] == arr [ i - 1 ] ) : NEW_LINE INDENT curr_count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( curr_count > max_count ) : NEW_LINE INDENT max_count = curr_count NEW_LINE res = arr [ i - 1 ] NEW_LINE DEDENT curr_count = 1 NEW_LINE DEDENT DEDENT if ( curr_count > max_count ) : NEW_LINE INDENT max_count = curr_count NEW_LINE res = arr [ n - 1 ] NEW_LINE DEDENT return res NEW_LINE DEDENT arr = [ 1 , 5 , 2 , 1 , 3 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( mostFrequent ( arr , n ) ) NEW_LINE