Least frequent element in an array | JavaScript 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 code
function leastFrequent ( arr , n ) { arr . sort ( ) ; let min_count = n + 1 , res = - 1 ; let curr_count = 1 ; for ( let i = 1 ; i < n ; i ++ ) { if ( arr [ i ] == arr [ i - 1 ] ) curr_count ++ ; else { if ( curr_count < min_count ) { min_count = curr_count ; res = arr [ i - 1 ] ; } curr_count = 1 ; } } if ( curr_count < min_count ) { min_count = curr_count ; res = arr [ n - 1 ] ; } return res ; } let arr = [ 1 , 3 , 2 , 1 , 2 , 2 , 3 , 1 ] ; let n = arr . length ; document . write ( leastFrequent ( arr , n ) ) ;