![]() |
VOOZH | about |
Given a string s, the task is to print the frequency of each of the characters of s in alphabetical order.
Example:
Input: s = "aabccccddd"
Output: a2b1c4d3
Since it is already in alphabetical order, the frequency
of the characters is returned for each character.
Input: s = "geeksforgeeks"
Output: e4f1g2k2o1r1s2
We run two nested loops. The outer loop runs through every character from 'a' to 'z' and inner loop runs for the string. For every character, we count its frequency by running through the string.
Note the CHAR_SIZE is alphabet size of input characters which is typically a constant. If we have only lower case characters, then CHAR_SIZE is 26 only. If we consider all ASCII characters, then CHAR_SIZE is 256.
e4f1g2k2o1r1s2
Note the CHAR_SIZE is alphabet size of input characters which is typically a constant. If we have only lower case characters, then CHAR_SIZE is 26 only. If we consider all ASCII characters, then CHAR_SIZE is 256.
e4f1g2k2o1r1s2
Create a count array to store frequency of each character. We are going to use characters as index in this array. The frequency of 'a' is going to be stored at index 0, 'b' at 1, and so on. To find the index of a character, we subtract character a's ASCII value from the ASCII value of the character.
After building the count array, traverse through all characters from 'a' to 'z' whether the frequency of that character is 0 or not. If not 0, then print the character along with its frequency and update its frequency to 0 in the count array. This is done so that the same character is not printed again.
This is the same approach as above, but instead of using library hash map, we use a count array to ensure that we get the fast results
e4f1g2k2o1r1s2