Given a string str, the task is to sort the string according to the frequency of each character, in ascending order. If two elements have the same frequency, then they are sorted in lexicographical order.
Input: str = “geeksforgeeks”
Frequency of characters: g2 e4 k2 s2 f1 o1 r1
Sorted characters according to frequency: f1 o1 r1 g2 k2 s2 e4
f, o, r occurs one time so they are ordered lexicographically and so are g, k and s.
Hence the final output is forggkksseeee.
Input: str = “abc”
Approach The idea is to store each character with its frequency in a vector of pairs and then sort the vector pairs according to the frequency stored. Finally, print the vector in order.
Below is the implementation of the above approach:
Time Complexity: O(n * log(n))
Auxiliary Space: O(n)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.