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:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Remove even frequency characters from the string
- Remove odd frequency characters from the string
- Maximum repeated frequency of characters in a given string
- String with frequency of characters in Lucas Sequence
- Character whose frequency is equal to the sum of frequencies of other characters of the given string
- Check if a string has all characters with same frequency with one variation allowed
- Check whether frequency of characters in a string makes Fibonacci Sequence
- Number of Positions to partition the string such that atleast m characters with same frequency are present in each substring
- Sort string of characters
- Maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency
- Sort string of characters using Stack
- Sort groups of numbers and characters separately in a String
- Minimum characters to be replaced to make frequency of all characters same
- Check if frequency of character in one string is a factor or multiple of frequency of same character in other string
- Check if frequency of all characters can become same by one removal
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : Yash_R