VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-characters-in-decreasing-order-of-frequency/

⇱ Print characters in decreasing order of frequency - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print characters in decreasing order of frequency

Last Updated : 12 Jul, 2025

Given string str, the task is to print the characters in decreasing order of their frequency. If the frequency of two characters is the 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 1: 
 

  • 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:
 


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

Approach 2 : We will make an array arr of size one more than the size of given string length in which we will store List of characters whose frequency is equal to the index of arr and follow the below steps :

  • Make a frequency map using array of characters present in the given string.
  • Traverse frequency array, if its value is greater than zero let say k.
  • On kth index of arr store it's character value in List at index 0(As we need descending order of alphabets if frequency is same).
  • Traverse arr from backwards as we need greater frequency first if List at that index is not empty then print its frequency and character.

Implementation of above approach :


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

Time Complexity : O(n), n is the length of given string

Auxiliary Space : O(n)

Comment