Least frequent element in an array | Python 3 program to find the least frequent element in an array . ; Sort the array ; find the min frequency using linear traversal ; If last element is least frequent ; Driver program
def leastFrequent ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE min_count = n + 1 NEW_LINE res = - 1 NEW_LINE 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 = curr_count + 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( curr_count < min_count ) : NEW_LINE INDENT min_count = curr_count NEW_LINE res = arr [ i - 1 ] NEW_LINE DEDENT curr_count = 1 NEW_LINE DEDENT DEDENT if ( curr_count < min_count ) : NEW_LINE INDENT min_count = curr_count NEW_LINE res = arr [ n - 1 ] NEW_LINE DEDENT return res NEW_LINE DEDENT arr = [ 1 , 3 , 2 , 1 , 2 , 2 , 3 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( leastFrequent ( arr , n ) ) NEW_LINE