Least frequent element in an array | PHP 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
< ? php function leastFrequent ( $ arr , $ n ) { sort ( $ arr ) ; sort ( $ arr , $ n ) ; $ min_count = $ n + 1 ; $ res = -1 ; $ curr_count = 1 ; for ( $ 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 ; } { $ arr = array ( 1 , 3 , 2 , 1 , 2 , 2 , 3 , 1 ) ; $ n = sizeof ( $ arr ) / sizeof ( $ arr [ 0 ] ) ; echo leastFrequent ( $ arr , $ n ) ; return 0 ; } ? >