VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-the-frequency-of-each-character-in-alphabetical-order/

⇱ Frequency of Characters in Alphabetical Order - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Frequency of Characters in Alphabetical Order

Last Updated : 16 Oct, 2024

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 

Naive Approach - O(n x CHAR_SIZE) Time and O(1) Space

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.


Output
e4f1g2k2o1r1s2

Expected Approach 1 - Using Hash Map or Dictionary - O(n) Time and O(CHAR_SIZE) Space

  1. Create a Hash Map and store the frequency of each of the characters of the given string.
  2. Finally, print the frequency of each of the character in alphabetical order.

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.


Output
e4f1g2k2o1r1s2

Expected Approach 2 - Using Count Array - O(n) Time and O(CHAR_SIZE) Space

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


Output
e4f1g2k2o1r1s2




Comment
Article Tags: