# Print the frequency of each character in Alphabetical order

Given a string str, the task is to print the frequency of each of the characters of str in alphabetical order.
Example:

Input: str = “aabccccddd”
Output: a2b1c4d3
Since it is already in alphabetical order, the frequency
of the characters is returned for each character.
Input: str = “geeksforgeeks”
Output: e4f1g2k2o1r1s2

Approach:

1. Create a Map to store the frequency of each of the characters of the given string.
2. Iterate through the string and check if the character is present in the map.
3. If the character is not present, insert it in the map with 1 as the initial value else increment its frequency by 1.
4. Finally, print the frequency of each of the character in alphabetical order.

Below is the implementation of the above approach:

## C++

 // C++ implementation of the approach#include using namespace std; const int MAX = 26; // Function to print the frequency// of each of the characters of// s in alphabetical ordervoid compressString(string s, int n){    // To store the frequency    // of the characters    int freq[MAX] = { 0 };     // Update the frequency array    for (int i = 0; i < n; i++) {        freq[s[i] - 'a']++;    }     // Print the frequency in alphatecial order    for (int i = 0; i < MAX; i++) {         // If the current alphabet doesn't        // appear in the string        if (freq[i] == 0)            continue;         cout << (char)(i + 'a') << freq[i];    }} // Driver codeint main(){    string s = "geeksforgeeks";    int n = s.length();     compressString(s, n);     return 0;}

## Java

 // Java implementation of the approach class GFG {         static int MAX = 26;          // Function to print the frequency     // of each of the characters of     // s in alphabetical order     static void compressString(String s, int n)     {         // To store the frequency         // of the characters         int freq[] = new int[MAX] ;              // Update the frequency array         for (int i = 0; i < n; i++)         {             freq[s.charAt(i) - 'a']++;         }              // Print the frequency in alphatecial order         for (int i = 0; i < MAX; i++)        {                  // If the current alphabet doesn't             // appear in the string             if (freq[i] == 0)                 continue;                  System.out.print((char)(i + 'a') +""+ freq[i]);         }     }          // Driver code     public static void main (String[] args)    {         String s = "geeksforgeeks";         int n = s.length();              compressString(s, n);     } } // This code is contributed by AnkitRai01

## Python3

 # Python3 implementation of the approach MAX = 26;  # Function to print the frequency # of each of the characters of # s in alphabetical order def compressString(s, n) :     # To store the frequency     # of the characters     freq = [ 0 ] * MAX;      # Update the frequency array     for i in range(n) :        freq[ord(s[i]) - ord('a')] += 1;      # Print the frequency in alphatecial order     for i in range(MAX) :          # If the current alphabet doesn't         # appear in the string         if (freq[i] == 0) :            continue;          print((chr)(i + ord('a')),freq[i],end = " ");  # Driver code if __name__ == "__main__" :      s = "geeksforgeeks";     n = len(s);      compressString(s, n);  # This code is contributed by AnkitRai01

## C#

 // C# implementation of the approach using System; class GFG {          static int MAX = 26;          // Function to print the frequency     // of each of the characters of     // s in alphabetical order     static void compressString(string s, int n)     {         // To store the frequency         // of the characters         int []freq = new int[MAX] ;              // Update the frequency array         for (int i = 0; i < n; i++)         {             freq[s[i] - 'a']++;         }              // Print the frequency in alphatecial order         for (int i = 0; i < MAX; i++)         {                  // If the current alphabet doesn't             // appear in the string             if (freq[i] == 0)                 continue;                  Console.Write((char)(i + 'a') +""+ freq[i]);         }     }          // Driver code     public static void Main()     {         string s = "geeksforgeeks";         int n = s.Length;              compressString(s, n);     } }  // This code is contributed by AnkitRai01

## Javascript



Output:
e4f1g2k2o1r1s2

Time Complexity: O(n)
Auxiliary Space: O(1)

Using Map(stl):-

The Approach:

The approach is very simple we are go on traversing and print the all the char with there frequency.

## C++

 #include #includeusing namespace std; int main() {     //given string.     string s = "geeksforgeeks";     //map char-int pair.     mapmp;     //map over string.     for(auto it:s)mp[it]++;     //printing the char with there frequency.     cout<<"All character in string with there frequency :"<

## Python3

 # Python program for the above approachs = "geeksforgeeks"# map of char-int pairmp = {} # map over stringfor i in range(len(s)):    if(mp.get(s[i]) != None):        mp[s[i]] = mp.get(s[i])+1    else:        mp[s[i]] = 1     # printing the char with frequencymyKeys = list(mp.keys())myKeys.sort()mp = {i : mp[i] for i in myKeys}for i in mp:    print(i, end="")    print(mp[i], end="")

## C#

 using System;using System.Collections.Generic; class GFG {    static void Main(string[] args) {        //given string.        string s = "geeksforgeeks";        //map char-int pair.        Dictionary mp = new Dictionary();        //map over string.        foreach (char c in s) {            if (mp.ContainsKey(c)) {                mp++;            } else {                mp = 1;            }        }        //printing the char with there frequency.        Console.WriteLine("All character in string with their frequency:");        foreach (KeyValuePair pair in mp) {            Console.Write(pair.Key + "" + pair.Value);        }    }} // code by ksam24000

## Javascript

 // JavaScript program for above approach// given stringlet s = "geeksforgeeks"; // map char-int pairlet mp = new Map(); // map over stringfor(let i = 0; i key1.localeCompare(key2))mp = new Map(sortedArray)mp.forEach(function(value, key){    console.log(key+value);}) // This code is contributed by Yash Agarwal(yashagarwal2852002)

## Java

 import java.util.*; public class Main {    public static void main(String[] args) {        // given string        String s = "geeksforgeeks";        // map char-int pair        Map mp = new TreeMap();        // map over string        for (char c : s.toCharArray()) {            if (mp.containsKey(c)) {                mp.put(c, mp.get(c) + 1);            } else {                mp.put(c, 1);            }        }        // printing the char with their frequency        System.out.println("All character in string with their frequency :");        for (Map.Entry entry : mp.entrySet()) {            System.out.print(entry.getKey() + "" + entry.getValue());        }    }}// ksam24000

Output
All character in string with there frequency :
e4f1g2k2o1r1s2

Complexity Analysis:

Time Complexity: O(n),for tarversing string.
Auxiliary Space: O(n),for map.

Approach 3: Recursive approach

Algorithm:

1. Take the string “s” as input and calculate size in n.
2. Run a loop from ‘a’ to ‘z’ and call the  “compressString” function for each time  with count = 0 to store the frequency of the letter.
3. The  “compressString” function check if counter i>size of the string then return the function else increment the count if character equal to s[i] and call the  “compressString” again with i+1;
4. Now check if count is not equal to 0 then print the letter with count.

## C++

 // C++ code for above approach#include using namespace std; // Recursive functionvoid compressString(string s, int n, int i, char letter, int &count){  // Base case: if i>size of string the return  if(i>n-1)    return;     // If the letter equal to the s[i] then increment count by 1  if(s[i]==letter)    count++;   // Call the recursive function again with i+1  compressString(s,n,i+1,letter,count);} // Driver codeint main(){       string s = "geeksforgeeks"; // input string    int n = s.length(); // size of string         for(char letter = 'a'; letter<='z'; letter++)    {        int count  = 0; // frequency counter                 // Call the recursive function        compressString(s,n,0,letter,count);                 if(count==0)  // if count equal to 0 continue.            continue;         cout<

## Java

 import java.util.*; class Main {         // Recursive function    static void compressString(String s, int n, int i, char letter, int[] count) {        // Base case: if i > size of string then return        if(i > n - 1) {            return;        }                 // If the letter is equal to s[i], then increment count by 1        if(s.charAt(i) == letter) {            count[0]++;        }                 // Call the recursive function again with i+1        compressString(s, n, i+1, letter, count);    }         // Driver code    public static void main(String[] args) {        String s = "geeksforgeeks"; // input string        int n = s.length(); // size of string                 for(char letter = 'a'; letter <= 'z'; letter++) {            int[] count = {0}; // frequency counter                         // Call the recursive function            compressString(s, n, 0, letter, count);                         if(count[0] == 0) { // if count is equal to 0, continue                continue;            }                         System.out.print(letter + "" + count[0]); // Print the letter with count.        }    }}

## C#

 using System; class GFG {    // Recursive function    static void compressString(string s, int n, int i,                               char letter, ref int count)    {        // Base case: if i>size of string the return        if (i > n - 1)            return;        // If the letter equal to the s[i] then increment        // count by 1        if (s[i] == letter)            count++;        // Call the recursive function again with i+1        compressString(s, n, i + 1, letter, ref count);    }     static void Main()    {        string s = "geeksforgeeks"; // input string        int n = s.Length; // size of string         for (char letter = 'a'; letter <= 'z'; letter++) {            int count = 0;            // Call the recursive function            compressString(s, n, 0, letter, ref count);            // if count equal to 0 continue.            if (count == 0)                continue;             // Print the letter with count.            Console.Write(letter);            Console.Write(count);        }    }}

## Python3

 # Recursive function to compress a stringdef compressString(s, n, i, letter, count):    # Base case: if i>size of string then return    if i > n - 1:        return     # If the letter is equal to the s[i], then increment count by 1    if s[i] == letter:        count += 1     # Call the recursive function again with i+1    compressString(s, n, i + 1, letter, count)     return count # Driver codeif __name__ == '__main__':    s = "geeksforgeeks" # input string    n = len(s) # size of string     for letter in range(ord('a'), ord('z') + 1):        letter = chr(letter)        count = compressString(s, n, 0, letter, 0)         if count == 0: # if count equal to 0 continue            continue         print(letter, count, end = '') # Print the letter with count

## Javascript

 // Recursive functionfunction compressString(s, n, i, letter, count) {  // Base case: if i > size of string then return  if (i > n - 1) {    return;  }   // If the letter is equal to s[i], then increment count by 1  if (s.charAt(i) === letter) {    count[0]++;  }   // Call the recursive function again with i+1  compressString(s, n, i + 1, letter, count);} // Driver codeconst s = "geeksforgeeks"; // input stringconst n = s.length; // size of stringans = "";for (let letter = "a"; letter <= "z"; letter = String.fromCharCode(letter.charCodeAt(0) + 1)) {  const count = [0]; // frequency counter   // Call the recursive function  compressString(s, n, 0, letter, count);   if (count[0] === 0) { // if count is equal to 0, continue    continue;  }   ans  = ans +letter + "" + count[0]; // Print the letter with count.} console.log(ans);

Output
e4f1g2k2o1r1s2

Time Complexity:  O(n)
Auxiliary Space:  O(1)

Previous
Next