Print characters in decreasing order of frequency

Given a string str, the task is to print the characters in decreasing order of their frequency. If the frequency of two characters is same then sort them in descending order alphabetically.

Examples:

Input: str = “geeksforgeeks”
Output:
e – 4
s – 2
k – 2
g – 2
r – 1
o – 1
f – 1



Input: str = “bbcc”
Output:
c – 2
b – 2

Approach:

  • Use an unordered_map to store the frequencies of all the elements of the given string.
  • Find the maximum frequency element from the map, print it with its frequency and remove it from the map.
  • Repeat the previous step while the map is not empty.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to print the characters
// of the given string in decreasing
// order of their frequencies
void printChar(string str, int len)
{
  
    // To store the
    unordered_map<char, int> occ;
    for (int i = 0; i < len; i++)
        occ[str[i]]++;
  
    // Map's size
    int size = occ.size();
    unordered_map<char, int>::iterator it;
  
    // While there are elements in the map
    while (size--) {
  
        // Finding the maximum value
        // from the map
        unsigned currentMax = 0;
        char arg_max;
        for (it = occ.begin(); it != occ.end(); ++it) {
            if (it->second > currentMax
                || (it->second == currentMax
                    && it->first > arg_max)) {
                arg_max = it->first;
                currentMax = it->second;
            }
        }
  
        // Print the character
        // alongwith its frequency
        cout << arg_max << " - " << currentMax << endl;
  
        // Delete the maximum value
        occ.erase(arg_max);
    }
}
  
// Driver code
int main()
{
  
    string str = "geeksforgeeks";
    int len = str.length();
  
    printChar(str, len);
  
    return 0;
}

chevron_right


Output:

e - 4
s - 2
k - 2
g - 2
r - 1
o - 1
f - 1


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.