Open In App

Frequency of Characters in Alphabetical Order

Last Updated : 16 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

C++
#include <bits/stdc++.h>
using namespace std;

string getCharFreq(string &s) {
    string res = "";
    int n = s.size();

    // Loop through characters from 'a' to 'z'
    for (char c = 'a'; c <= 'z'; c++) {
        int count = 0; 

        // Inner loop to count occurrences of character c
        for (int j = 0; j < n; j++) {
            if (s[j] == c) {
                count++;
            }
        }

        // If the character appears in the string, append 
        // it and its frequency to the result
        if (count > 0) {
            res += c + to_string(count);
        }
    }

    return res;
}

int main() {
    string s = "geeksforgeeks";
    cout << getCharFreq(s) << endl;
    return 0;
}

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.

C++
#include <bits/stdc++.h>
using namespace std;

string getCharFreq(string &s) {    

    // count frequency of each character
    unordered_map<char, int> freq;
    for (char c : s) {
        freq[c]++;
    }

    string res = "";

    for (char c = 'a'; c <= 'z'; c++) {
        if (freq[c] > 0) {
          
            // append character and its frequency
            res += c + to_string(freq[c]);
        }
    }

    return res;
}

int main() {
    string s = "geeksforgeeks";
    cout << getCharFreq(s) << endl;
    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
Python
# 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
<script>

    // Javascript implementation of the approach 
    
    let MAX = 26; 
      
    // Function to print the frequency 
    // of each of the characters of 
    // s in alphabetical order 
    function compressString(s, n) 
    { 
        // To store the frequency 
        // of the characters 
        let freq = new Array(MAX); 
        freq.fill(0);
      
        // Update the frequency array 
        for (let i = 0; i < n; i++) 
        { 
            freq[s[i].charCodeAt() - 'a'.charCodeAt()]++; 
        } 
      
        // Print the frequency in alphatecial order 
        for (let i = 0; i < MAX; i++)
        { 
      
            // If the current alphabet doesn't 
            // appear in the string 
            if (freq[i] == 0) 
                continue; 
      
            document.write(String.fromCharCode(i + 
            'a'.charCodeAt()) +""+ freq[i]); 
        } 
    } 
    
    let s = "geeksforgeeks"; 
    let n = s.length; 

    compressString(s, n); 
    
</script>

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

C++
#include <bits/stdc++.h>
using namespace std;

const int CHAR_SIZE = 26;

string getCharFreq(string &s) {    
  
    // count frequency of each character
    int freq[CHAR_SIZE] = {0};
    for (char c : s) {
        freq[c - 'a']++;
    }

    string res = "";

    for (char c = 'a'; c <= 'z'; c++) {
        if (freq[c - 'a'] > 0) {
          
            // Append character and its frequency
            res += c + to_string(freq[c - 'a']);
            
            // Mark as processed
            freq[c - 'a'] = 0;
        }
    }

    return res;
}

int main() {
    string s = "geeksforgeeks";
    cout << getCharFreq(s) << endl;  
    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
Python
# 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
<script>

    // Javascript implementation of the approach 
    
    let MAX = 26; 
      
    // Function to print the frequency 
    // of each of the characters of 
    // s in alphabetical order 
    function compressString(s, n) 
    { 
        // To store the frequency 
        // of the characters 
        let freq = new Array(MAX); 
        freq.fill(0);
      
        // Update the frequency array 
        for (let i = 0; i < n; i++) 
        { 
            freq[s[i].charCodeAt() - 'a'.charCodeAt()]++; 
        } 
      
        // Print the frequency in alphatecial order 
        for (let i = 0; i < MAX; i++)
        { 
      
            // If the current alphabet doesn't 
            // appear in the string 
            if (freq[i] == 0) 
                continue; 
      
            document.write(String.fromCharCode(i + 
            'a'.charCodeAt()) +""+ freq[i]); 
        } 
    } 
    
    let s = "geeksforgeeks"; 
    let n = s.length; 

    compressString(s, n); 
    
</script>

Output
e4f1g2k2o1r1s2





Next Article

Similar Reads