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:
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.
- Sort an array of Strings according frequency
- Maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency
- Check if frequency of character in one string is a factor or multiple of frequency of same character in other string
- Sort a string according to the order defined by another string
- Minimum characters to be replaced to make frequency of all characters same
- Sort an array of strings according to string lengths
- Sort the array of strings according to alphabetical order defined by another string
- Sort an array of strings according to string lengths using Map
- Generate a number such that the frequency of each digit is digit times the frequency in given number
- Count of Binary Strings of length N such that frequency of 1's exceeds frequency of 0's
- Maximum difference between frequency of two elements such that element having greater frequency is also greater
- Comparison among Bubble Sort, Selection Sort and Insertion Sort
- Sort an array according to the order defined by another array
- Sort an array according to absolute difference with a given value "using constant extra space"
- Python | Sort a List according to the Length of the Elements
- Python | Sort a list according to the second element in sublist
- Python | Sort an array according to absolute difference
- Sort the numbers according to their sum of digits
- Sort an array according to count of set bits | Set 2
- Sort an array according to absolute difference with given value using Functors
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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