VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-characters-frequencies-order-occurrence/

⇱ Find Character Frequencies in Order of Occurrence - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find Character Frequencies in Order of Occurrence

Last Updated : 14 Nov, 2024

Given string s containing only lowercase characters, the task is to print the characters along with their frequency in the order of their occurrence and in the given format explained in the examples below.

Examples:

Input: s = "geeksforgeeks"
Output: g2 e4 k2 s2 f1 o1 r1

Input: str = "elephant"
Output: e2 l1 p1 h1 a1 n1 t1

Source:SAP Interview Experience | Set 26

[Naive Approach] Using Nested Loops - O(n^2) Time and O(1) Space

Traverse through every character and count frequency of it using one more loop inside the main traversal loop. To ensure that we do not have repeated characters in output, check if the character is already seen. If already seen, then ignore the character.


Output
g2 e4 k2 s2 f1 o1 r1 

[Expected Approach 1] Use Hash Map or Dictionary - O(n) Time and O(MAX_CHAR) Space

1) Store Frequencies of all characters in a map.
2) Traverse through the string, append the character and its frequency to the result and make frequency as 0 to avoid repetition.

Note the MAX_CHAR is alphabet size of input characters which is typically a constant. If we have only lower case characters, then MAX_CHAR is 26 only. If we consider all ASCII characters, then MAX_CHAR is 256.


Output
g2 e4 k2 s2 f1 o1 r1 

[Expected Approach 2] Use Frequency Array - O(n) Time and O(MAX_CHAR) Space

Create a frequency 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.

Traverse the string again and check 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 frequency 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 an array to ensure that we get the fast results.


Output
g2e4k2s2f1o1r1


Using Counter in Python


Comment
Article Tags: