Open In App

Find Character Frequencies in Order of Occurrence

Last Updated : 14 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

C++
// C++ Code to find character frequencies in order of
// occurrence using Nested Loops

#include <iostream>
using namespace std;

// function to modify the string by appending 
// character with its frequency in order of occurrence
string modifyString(string &s) {
    
    string res = "";
    int n = s.size();
    
    // loop through the string
    for (int i = 0; i < n; i++) {
        
        // count the occurrence of s[i]
        int count = 1;  
        
        // check if the character has been 
        // processed already
        bool seen = false;
        for (int j = 0; j < i; j++) {
            if (s[j] == s[i]) {
                seen = true;
                break;
            }
        }
        
        if (seen) continue; 
        
        // count frequency of s[i]
        for (int j = i + 1; j < n; j++) {
            if (s[j] == s[i]) {
                count++;
            }
        }
        
        // append character and its frequency 
        // to the result
        res += s[i] + to_string(count) + " ";
    }
    
    return res;
}

int main() {
    string s = "geeksforgeeks";
    cout << modifyString(s);
    return 0;
}
Java
// Java Code to find character frequencies in order of
// occurrence using Nested Loops
import java.util.*;
class GfG {
  
  	// function to modify the string by appending 
	// character with its frequency in order of occurrence
    static String modifyString(String s) {
    
        String res = "";
        int n = s.length();
        
        // loop through the string
        for (int i = 0; i < n; i++) {
            
            // count the occurrence of s[i]
            int count = 1;  
            
            // check if the character has been 
            // processed already
            boolean seen = false;
            for (int j = 0; j < i; j++) {
                if (s.charAt(j) == s.charAt(i)) {
                    seen = true;
                    break;
                }
            }
            
            if (seen) continue; 
        
            // count frequency of s[i]
            for (int j = i + 1; j < n; j++) {
                if (s.charAt(j) == s.charAt(i)) {
                    count++;
                }
            }
            
            // append character and its frequency 
            // to the result
            res += s.charAt(i) + Integer.toString(count) + " ";
        }
    
        return res;
    }

    public static void main(String[] args) {
        String s = "geeksforgeeks";
        System.out.println(modifyString(s));
    }
}
Python
# Python Code to find character frequencies in order of
# occurrence using Nested Loops

# function to modify the string by appending 
# character with its frequency in order of occurrence
def modifyString(s):
    
    res = ""
    n = len(s)
    
    # loop through the string
    for i in range(n):
        
        # count the occurrence of s[i]
        count = 1  
        
        # check if the character has been 
        # processed already
        seen = False
        for j in range(i):
            if s[j] == s[i]:
                seen = True
                break
        
        if seen: continue; 
        
        # count frequency of s[i]
        for j in range(i + 1, n):
            if s[j] == s[i]:
                count += 1
        
        # append character and its frequency 
        # to the result
        res += s[i] + str(count) + " "
    
    return res

s = "geeksforgeeks"
print(modifyString(s))
C#
// C# Code to find character frequencies in order of
// occurrence using Nested Loops
using System;

class GfG {
  
  	// function to modify the string by appending 
	// character with its frequency in order of occurrence
    static string modifyString(string s) {
    
        string res = "";
        int n = s.Length;
        
        // loop through the string
        for (int i = 0; i < n; i++) {
            
            // count the occurrence of s[i]
            int count = 1;  
            
            // check if the character has been 
            // processed already
            bool seen = false;
            for (int j = 0; j < i; j++) {
                if (s[j] == s[i]) {
                    seen = true;
                    break;
                }
            }
            
            if (seen) continue; 
        
            // count frequency of s[i]
            for (int j = i + 1; j < n; j++) {
                if (s[j] == s[i]) {
                    count++;
                }
            }
            
            // append character and its frequency 
            // to the result
            res += s[i] + count.ToString() + " ";
        }
    
        return res;
    }

    static void Main(string[] args) {
        string s = "geeksforgeeks";
        Console.WriteLine(modifyString(s));
    }
}
JavaScript
// JavaScript Code to find character frequencies in order of
// occurrence using Nested Loops

// function to modify the string by appending 
// character with its frequency in order of occurrence
function modifyString(s) {
    
    let res = "";
    let n = s.length;
        
    // loop through the string
    for (let i = 0; i < n; i++) {
        
        // count the occurrence of s[i]
        let count = 1;  
        
        // check if the character has been 
        // processed already
        let seen = false;
        for (let j = 0; j < i; j++) {
            if (s[j] === s[i]) {
                seen = true;
                break;
            }
        }
        
        if (seen) continue; 
        
        // count frequency of s[i]
        for (let j = i + 1; j < n; j++) {
            if (s[j] === s[i]) {
                count++;
            }
        }
        
        // append character and its frequency 
        // to the result
        res += s[i] + count.toString() + " ";
    }
    
    return res;
}

let s = "geeksforgeeks";
console.log(modifyString(s));

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.

C++
// C++ Code to find character frequencies in order of
// occurrence using Hash Map
#include <iostream>
#include<unordered_map>
using namespace std;

// function to return the characters and
// frequencies in the order of their occurrence
string modifyString(string &s) {
    unordered_map<char, int> d;
    string res = "";

    // Store all characters and their frequencies
    for (char i : s) {
        d[i]++;
    }

    // Build the result string with characters 
    // and their frequencies
    for (char i : s) {
        if (d[i] != 0) {
          
            // append character and frequency
            res += i + to_string(d[i]) + " "; 
          
            // mark as processed
            d[i] = 0; 
        }
    }

    return res;
}

int main() {
    string s = "geeksforgeeks";
    cout << modifyString(s);
    return 0;
}
Java
// Java Code to find character frequencies in order of
// occurrence using Hash Map
import java.util.*;
class Gfg {
    public static void modifyString(String s)
    {

        // Store all characters and
        // their frequencies in dictionary
        Map<Character, Integer> d
            = new HashMap<Character, Integer>();

        for (int i = 0; i < s.length(); i++) {
            if (d.containsKey(s.charAt(i))) {
                d.put(s.charAt(i), d.get(s.charAt(i)) + 1);
            }
            else {
                d.put(s.charAt(i), 1);
            }
        }

        // Print characters and their
        // frequencies in same order
        // of their appearance
        for (int i = 0; i < s.length(); i++) {

            // Print only if this
            // character is not printed
            // before
            if (d.get(s.charAt(i)) != 0) {
                System.out.print(s.charAt(i));
                System.out.print(d.get(s.charAt(i)) + " ");
                d.put(s.charAt(i), 0);
            }
        }
    }

    // Driver code
    public static void main(String[] args)
    {
        String S = "geeksforgeeks";
        modifyString(S);
    }
}
Python
# Python Code to find character frequencies in order of
# occurrence using Hash Map
def modifyString(str):

    # Store all characters and their frequencies
    # in dictionary
    d = {}
    for i in str:
        if i in d:
            d[i] += 1
        else:
            d[i] = 1
    
    # Print characters and their frequencies in
    # same order of their appearance
    for i in str:

        # Print only if this character is not printed
        # before.  
        if d[i] != 0:
            print("{}{}".format(i,d[i]), end =" ")
            d[i] = 0
     
if __name__ == "__main__" :
    
    str = "geeksforgeeks";
    modifyString(str);
    
C#
// C# Code to find character frequencies in order of
// occurrence using Hash Map
using System;
using System.Collections;
using System.Collections.Generic;

class GFG {

    public static void modifyString(string s)
    {

        // Store all characters and
        // their frequencies in dictionary
        Dictionary<char, int> d
            = new Dictionary<char, int>();

        foreach(char i in s)
        {
            if (d.ContainsKey(i)) {
                d[i]++;
            }
            else {
                d[i] = 1;
            }
        }

        // Print characters and their
        // frequencies in same order
        // of their appearance
        foreach(char i in s)
        {
            // Print only if this
            // character is not printed
            // before
            if (d[i] != 0) {
                Console.Write(i + d[i].ToString() + " ");
                d[i] = 0;
            }
        }
    }

    // Driver Code
    public static void Main(string[] args)
    {
        string s = "geeksforgeeks";
        modifyString(s);
    }
}

// This code is contributed by pratham76
JavaScript
// JavaScript Code to find character frequencies in order of
// occurrence using Hash Map
function modifyString(s) {
    let d = {};
    let res = "";

    // Store all characters and their frequencies
    for (let i of s) {
        d[i] = (d[i] || 0) + 1;
    }

    // Build the result string with characters 
    // and their frequencies
    for (let i of s) {
        if (d[i] !== 0) {
          
            // append character and frequency
            res += i + d[i] + " "; 
          
            // mark as processed
            d[i] = 0; 
        }
    }

    return res;
}

function main() {
    let s = "geeksforgeeks";
    console.log(modifyString(s));
}

main();

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.

C++
// C++ Code to find character frequencies in order of
// occurrence using Frequency Array
#include <iostream>
using namespace std;

const int MAX_CHAR=26;

// function to modify the string by appending 
// character with its frequency in order of occurrence
string modifyString(string &s) {
  
    // Store frequencies of all characters
    int freq[MAX_CHAR] = {0}; 
    for (char c : s)
        freq[c - 'a']++;

    string res = ""; 
    for (char c : s) {
        if (freq[c - 'a'] != 0) {
          
            // append character and frequency
            res += c + to_string(freq[c - 'a'])+" ";  
          
            // mark as processed
            freq[c - 'a'] = 0;
        }
    }
    return res;
}

int main() {
    string s = "geeksforgeeks";
    cout << modifyString(s);
    return 0;
}
Java
// Java implementation to print the character and
// its frequency in order of its occurrence
public class Char_frequency {
    
    static final int MAX_CHAR = 26;
     
    // function to print the character and its 
    // frequency in order of its occurrence
    static void printCharWithFreq(String str)
    {
         // size of the string 'str'
        int n = str.length();

        // 'freq[]' implemented as hash table
        int[] freq = new int[MAX_CHAR];

        // accumulate frequency of each character
        // in 'str'
        for (int i = 0; i < n; i++)
            freq[str.charAt(i) - 'a']++;

        // traverse 'str' from left to right
        for (int i = 0; i < n; i++) {

            // if frequency of character str.charAt(i)
            // is not equal to 0
            if (freq[str.charAt(i) - 'a'] != 0) {

                // print the character along with its
                // frequency
                System.out.print(str.charAt(i));
                System.out.print(freq[str.charAt(i) - 'a'] + " "); 

                // update frequency of str.charAt(i) to 
                // 0 so that the same character is not
                // printed again
                freq[str.charAt(i) - 'a'] = 0;
            }
        }
    }
     
    // Driver program to test above
    public static void main(String args[])
    {
        String str = "geeksforgeeks";
        printCharWithFreq(str);
    }
}
Python
# C++ Code to find character frequencies in order of
# occurrence using Frequency Array
MAX_CHAR = 26

# function to modify the string by appending
# character with its frequency in order of occurrence
def modifyString(s):
  
    # Store frequencies of all characters
    freq = [0] * MAX_CHAR
    for c in s:
        freq[ord(c) - ord('a')] += 1
    
    res = ""
    for c in s:
        if freq[ord(c) - ord('a')] != 0:
          
            # append character and frequency
            res += c + str(freq[ord(c) - ord('a')]) + " "
            
            # mark as processed
            freq[ord(c) - ord('a')] = 0
    
    return res

s = "geeksforgeeks"
print(modifyString(s))
C#
// C++ Code to find character frequencies in order of
// occurrence using Frequency Array
using System;

class GFG {
    static int MAX_CHAR = 26;

    // function to print the character and its
    // frequency in order of its occurrence
    static void printCharWithFreq(String str)
    {
        // size of the string 'str'
        int n = str.Length;

        // 'freq[]' implemented as hash table
        int[] freq = new int[MAX_CHAR];

        // accumulate frequency of each character
        // in 'str'
        for (int i = 0; i < n; i++)
            freq[str[i] - 'a']++;

        // traverse 'str' from left to right
        for (int i = 0; i < n; i++) {

            // if frequency of character str.charAt(i)
            // is not equal to 0
            if (freq[str[i] - 'a'] != 0) {

                // print the character along with its
                // frequency
                Console.Write(str[i]);
                Console.Write(freq[str[i] - 'a'] + " ");

                // update frequency of str.charAt(i) to
                // 0 so that the same character is not
                // printed again
                freq[str[i] - 'a'] = 0;
            }
        }
    }

    public static void Main()
    {
        String str = "geeksforgeeks";
        printCharWithFreq(str);
    }
}
JavaScript
// C++ Code to find character frequencies in order of
// occurrence using Frequency Array
function modifyString(s) {

    // Store frequencies of all characters
    let freq = new Array(26).fill(0);
    for (let c of s) {
        freq[c.charCodeAt(0) - 'a'.charCodeAt(0)]++;
    }

    let res = ""; 
    for (let c of s) {
        if (freq[c.charCodeAt(0) - 'a'.charCodeAt(0)] !== 0) {

            // append character and frequency
            res += c + freq[c.charCodeAt(0) - 'a'.charCodeAt(0)] + " "; 

            // mark as processed
            freq[c.charCodeAt(0) - 'a'.charCodeAt(0)] = 0;
        }
    }
    return res;
}

let s = "geeksforgeeks";
console.log(modifyString(s));

Output
g2e4k2s2f1o1r1


Using Counter in Python

Python
from collections import Counter

def prCharWithFreq(s):
  
    # Count the frequency of each character
    freq = Counter(s)
    
    res = ""
    
    # Iterate over the string and append characters 
    # with their frequencies
    for char in s:
        if freq[char] != 0:
            res += char + str(freq[char]) + " "
            freq[char] = 0  # mark as processed

    return res

# Driver code
s = "geeksforgeeks"
print(prCharWithFreq(s))



Next Article
Article Tags :
Practice Tags :

Similar Reads