Count frequencies of all elements in array in O ( 1 ) extra space and O ( n ) time | Function to find counts of all elements present in arr [ 0. . n - 1 ] . The array elements must be range from 1 to n ; Subtract 1 from every element so that the elements become in range from 0 to n - 1 ; Use every element arr [ i ] as index and add ' n ' to element present at arr [ i ] % n to keep track of count of occurrences of arr [ i ] ; To print counts , simply print the number of times n was added at index corresponding to every element ; Driver code
def printfrequency ( arr , n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT arr [ j ] = arr [ j ] - 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT arr [ arr [ i ] % n ] = arr [ arr [ i ] % n ] + n NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( i + 1 , " - > " , arr [ i ] // n ) NEW_LINE DEDENT DEDENT arr = [ 2 , 3 , 3 , 2 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE printfrequency ( arr , n ) NEW_LINE