![]() |
VOOZH | about |
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
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.
g2 e4 k2 s2 f1 o1 r1
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.
g2 e4 k2 s2 f1 o1 r1
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.
g2e4k2s2f1o1r1