Find frequency of each element in a limited range array in less than O ( n ) time | python program to count number of occurrences of each element in the array in O ( n ) time and O ( 1 ) space ; check if the current element is equal to previous element . ; reset the frequency ; print the last element and its frequency ;
def findFrequencies ( ele , n ) : NEW_LINE INDENT freq = 1 NEW_LINE idx = 1 NEW_LINE element = ele [ 0 ] NEW_LINE while ( idx < n ) : NEW_LINE INDENT if ( ele [ idx - 1 ] == ele [ idx ] ) : NEW_LINE INDENT freq += 1 NEW_LINE idx += 1 NEW_LINE DEDENT else : NEW_LINE INDENT print ( element , " ▁ " , freq ) ; NEW_LINE element = ele [ idx ] NEW_LINE idx += 1 NEW_LINE freq = 1 NEW_LINE DEDENT DEDENT print ( element , " ▁ " , freq ) ; NEW_LINE DEDENT / * Driver code * / NEW_LINE print ( " - - - frequencies ▁ in ▁ a ▁ sorted ▁ array - - - - " ) ; NEW_LINE arr = [ 10 , 20 , 30 , 30 , 30 , 40 , 50 , 50 , 50 , 50 , 70 ] ; NEW_LINE n = len ( arr ) NEW_LINE findFrequencies ( arr , n ) NEW_LINE