Skip to content
Related Articles

Related Articles

Sort a string according to the frequency of characters

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 19 Jul, 2022
View Discussion
Improve Article
Save Article

Given a string str, the task is to sort the string according to the frequency of each character, in ascending order. If two elements have the same frequency, then they are sorted in lexicographical order.
Examples: 

Input: str = “geeksforgeeks” 
Output: forggkksseeee 
Explanation: 
Frequency of characters: g2 e4 k2 s2 f1 o1 r1 
Sorted characters according to frequency: f1 o1 r1 g2 k2 s2 e4 
f, o, r occurs one time so they are ordered lexicographically and so are g, k and s. 
Hence the final output is forggkksseeee.
Input: str = “abc” 
Output: abc 

Approach The idea is to store each character with its frequency in a vector of pairs and then sort the vector pairs according to the frequency stored. Finally, print the vector in order.
Below is the implementation of the above approach:  

C++




// C++ implementation to Sort strings
// according to the frequency of
// characters in ascending order
 
#include <bits/stdc++.h>
using namespace std;
 
// Returns count of character in the string
int countFrequency(string str, char ch)
{
    int count = 0;
 
    for (int i = 0; i < str.length(); i++)
 
        // Check for vowel
        if (str[i] == ch)
            ++count;
 
    return count;
}
 
// Function to sort the string
// according to the frequency
void sortArr(string str)
{
    int n = str.length();
 
    // Vector to store the frequency of
    // characters with respective character
    vector<pair<int, char> > vp;
 
    // Inserting frequency
    // with respective character
    // in the vector pair
    for (int i = 0; i < n; i++) {
 
        vp.push_back(
            make_pair(
                countFrequency(str, str[i]),
                str[i]));
    }
 
    // Sort the vector, this will sort the pair
    // according to the number of characters
    sort(vp.begin(), vp.end());
 
    // Print the sorted vector content
    for (int i = 0; i < vp.size(); i++)
        cout << vp[i].second;
}
 
// Driver code
int main()
{
    string str = "geeksforgeeks";
 
    sortArr(str);
 
    return 0;
}


Python3




# Python3 implementation to Sort strings
# according to the frequency of
# characters in ascending order
 
# Returns count of character in the string
def countFrequency(string ,  ch) :
 
    count = 0;
 
    for i in range(len(string)) :
 
        # Check for vowel
        if (string[i] == ch) :
            count += 1;
 
    return count;
 
# Function to sort the string
# according to the frequency
def sortArr(string) :
    n = len(string);
 
    # Vector to store the frequency of
    # characters with respective character
    vp = [];
 
    # Inserting frequency
    # with respective character
    # in the vector pair
    for i in range(n) :
 
        vp.append((countFrequency(string, string[i]), string[i]));
         
    # Sort the vector, this will sort the pair
    # according to the number of characters
    vp.sort();
     
    # Print the sorted vector content
    for i in range(len(vp)) :
        print(vp[i][1],end="");
 
# Driver code
if __name__ == "__main__" :
 
    string = "geeksforgeeks";
 
    sortArr(string);
 
    # This code is contributed by Yash_R


Javascript




<script>
 
// JavaScript implementation of the above approach
 
// Returns count of character in the string
function countFrequency(str, ch)
{
    var count = 0;
 
    for (var i = 0; i < str.length; i++)
 
        // Check for vowel
        if (str[i] == ch)
            ++count;
 
    return count;
}
 
// Function to sort the string
// according to the frequency
function sortArr(str)
{
    var n = str.length;
 
    // Vector to store the frequency of
    // characters with respective character
    vp = new Array(n);
 
    // Inserting frequency
    // with respective character
    // in the vector pair
    for (var i = 0; i < n; i++) {
 
        vp[i] = [countFrequency(str, str[i]), str[i]];
    }
 
    // Sort the vector, this will sort the pair
    // according to the number of characters
    vp.sort();
 
    // Print the sorted vector content
    for (var i = 0; i < n; i++)
        document.write(vp[i][1]);
}
 
// Driver Code
 
// Array of points
let str = "geeksforgeeks";
sortArr(str);
 
</script>


Output

forggkksseeee

Time Complexity: O(n2)

Auxiliary Space: O(n)

Method 2: (Optimized Approach – Min Heap Based)

Algorithm:

1. Take the the frequency of each character into a map.

2 .Take a MIN Heap, store in FREQUENCY, CHAR

3. After all insertions, Topmost element is the less frequent character

4. We keep a CUSTOM COMPARATOR for LESS FREQ, WHEN SAME FREQ – Ascending Order Characters.

5. Then Pop one by one and append in ANS String for FREQ no. of times.

CODE:

C++




#include <bits/stdc++.h>
using namespace std;
 
//O(N*LogN) Time, O(Distinct(N)) Space
//MIN HEAP Based - as we need less frequent element first
#define ppi pair<int,char>
 
//CUSTOM COMPARATOR for Heap
class Compare{
  public:
  //Override
  bool operator()(pair<int,char>below, pair<int,char> above){
    if(below.first == above.first){
      //freq same
      return below.second > above.second; //lexicographicaly smaller is TOP
    }
    return below.first > above.first; //less freq at TOP
  }
};
 
string frequencySort(string s) {
 
  unordered_map<char,int> mpp;
  priority_queue<ppi,vector<ppi>,Compare> minH; // freq , character
 
  for(char ch : s){
    mpp[ch]++;
  }
 
  for(auto m : mpp){
    minH.push({m.second, m.first}); // as freq is 1st , char is 2nd
  }
 
  string ans="";
  //Now we have in the TOP - Less Freq chars
 
  while(minH.size()>0){
 
    int freq = minH.top().first;
    char ch = minH.top().second;
    for(int i=0; i<freq; i++){
      ans+=ch; // append as many times of freq
    }
    minH.pop(); //Heapify happens 
  }
 
  return ans;
 
}
 
// Driver code
int main()
{
    string str = "geeksforgeeks";
  
    cout<<frequencySort(str)<<"\n";
  
    return 0;
}
 
//Code is Contributed by Balakrishnan R (rbkraj000)


Output

forggkksseeee

Time Complexity:

O(N+ N* Log N + N* Log N)  =  O(N* Log N) 

Reason:

  • 1 insertion in heap takes O(Log N), For N insertions O(N*LogN). (HEAP = Priority Queue)
  • 1 deletion in heap takes O(Log N), For N insertions O(N*LogN).
  • Unordered Map takes O(1) for 1 Insertion. 
  • N is the length of the String S (input)

Extra Space Complexity:

O(N)

Reason:

  • Map takes O(Distinct(N)) Space.
  • Heap also takes O(Distinct(N)) Space.
  • N is the length of the String S (input)

The Code, Approach, and Idea are proposed by Balakrishnan R (rbkraj000 GFG ID)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!