# Sort a string according to the frequency of characters

Last Updated : 26 Apr, 2023

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 #include   // Returns count of character in the string int countFrequency(char str[], char ch) {     int count = 0;       for (int i = 0; i < strlen(str); i++) {         // Check for vowel         if (str[i] == ch)             ++count;     }       return count; }   // Function to sort the string // according to the frequency void sortArr(char str[]) {     int n = strlen(str);       // Array of pairs to store the frequency of     // characters with respective character     struct Pair {         int count;         char ch;     } pairs[n];       int numOfPairs = 0;       // Inserting frequency     // with respective character     // in the array of pairs     for (int i = 0; i < n; i++) {         int count = countFrequency(str, str[i]);           int found = 0;         for (int j = 0; j < numOfPairs; j++) {             if (pairs[j].ch == str[i]) {                 pairs[j].count = count;                 found = 1;                 break;             }         }           if (!found) {             pairs[numOfPairs].count = count;             pairs[numOfPairs].ch = str[i];             numOfPairs++;         }     }       // Sort the array of pairs, this will sort the pair     // according to the number of characters     for (int i = 0; i < numOfPairs - 1; i++) {         for (int j = i + 1; j < numOfPairs; j++) {             if (pairs[i].count > pairs[j].count) {                 struct Pair temp = pairs[i];                 pairs[i] = pairs[j];                 pairs[j] = temp;             }         }     }       // Print the sorted array of pairs content     for (int i = 0; i < numOfPairs; i++) {         for (int j = 0; j < pairs[i].count; j++) {             printf("%c", pairs[i].ch);         }     } }   // Driver code int main() {     char str[] = "geeksforgeeks";       sortArr(str);       return 0; }

## C++

 // C++ implementation to Sort strings // according to the frequency of // characters in ascending order   #include 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 > 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; }

## Java

 import java.util.*;   class GFG {     // Returns count of character in the string     static int countFrequency(String str, char ch)     {         int count = 0;           for (int i = 0; i < str.length(); i++) {             // Check for character             if (str.charAt(i) == ch) {                 ++count;             }         }           return count;     }       // Function to sort the string according to the     // frequency of characters in ascending order     static void sortArr(String str)     {         int n = str.length();           // Dictionary to store the frequency of characters         Map freqDict             = new HashMap();           // Count the frequency of each character in the         // input string         for (int i = 0; i < n; i++) {             if (freqDict.containsKey(str.charAt(i))) {                 freqDict.put(str.charAt(i),                              freqDict.get(str.charAt(i))                                  + 1);             }             else {                 freqDict.put(str.charAt(i), 1);             }         }           // Sort the dictionary by value (frequency) in         // ascending order         List > sortedDict             = new ArrayList >(                 freqDict.entrySet());         Collections.sort(             sortedDict,             new Comparator<                 Map.Entry >() {                 public int compare(                     Map.Entry o1,                     Map.Entry o2)                 {                     return (o1.getValue()                             == (o2.getValue()))                         ? o1.getKey() - o2.getKey()                         : o1.getValue() - o2.getValue();                 }             });           // Print the sorted characters in the order of their         // frequency         for (Map.Entry entry :              sortedDict) {             for (int i = 0; i < entry.getValue(); i++) {                 System.out.print(entry.getKey());             }         }     }       // Driver code     public static void main(String[] args)     {         String str = "geeksforgeeks";                 // Driver code         sortArr(str);     } }

## 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

## C#

 using System; using System.Collections.Generic; using System.Linq;   public class Program {   // Returns count of character in the string   static int countFrequency(string str, char ch)   {     int count = 0;       for (int i = 0; i < str.Length; i++)     {       // Check for character       if (str[i] == ch)       {         ++count;       }     }       return count;   }     // Function to sort the string according to the   // frequency of characters in ascending order   static void sortArr(string str)   {     int n = str.Length;       // Dictionary to store the frequency of characters     Dictionary freqDict = new Dictionary();       // Count the frequency of each character in the input string     for (int i = 0; i < n; i++)     {       if (freqDict.ContainsKey(str[i]))       {         freqDict[str[i]]++;       }       else       {         freqDict[str[i]] = 1;       }     }       // Sort the dictionary by value (frequency) in ascending order     var sortedDict = freqDict.OrderBy(x => x.Value);       // Print the sorted characters in the order of their frequency     foreach (var kvp in sortedDict)     {       for (int i = 0; i < kvp.Value; i++)       {         Console.Write(kvp.Key);       }     }   }     // Driver code   static void Main(string[] args)   {     string str = "geeksforgeeks";       sortArr(str);   } }

## Javascript



Output

forggkksseeee

Time Complexity: O(n2)

Auxiliary Space: O(n)

### Method 2: (Optimized Approach – Min Heap Based)

Algorithm:

1. Take 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.

## C

 #include #include #include #include   // O(N*LogN) Time, O(Distinct(N)) Space // MIN HEAP Based - as we need less frequent element first typedef struct {     int first;     char second; } ppi;   // CUSTOM COMPARATOR for Heap bool compare(ppi below, ppi above) {     if (below.first == above.first) {         // freq same         return below.second > above.second; // lexicographically                                             // smaller is TOP     }     return below.first > above.first; // less freq at TOP }   char* frequencySort(char* s) {     int i;     int n = strlen(s);     char* ans = (char*)malloc(sizeof(char) * (n + 1));     memset(ans, '\0', sizeof(char) * (n + 1));       int* mpp = (int*)calloc(sizeof(int), 256);     ppi* arr = (ppi*)malloc(sizeof(ppi) * 256);     int k = 0;       for (i = 0; i < n; i++) {         mpp[s[i]]++;     }       for (i = 0; i < 256; i++) {         if (mpp[i]) {             arr[k].first = mpp[i];             arr[k].second = i;             k++;         }     }       ppi* heap = (ppi*)malloc(sizeof(ppi) * k);     for (i = 0; i < k; i++) {         heap[i] = arr[i];     }       int heapSize = k;     for (i = heapSize / 2; i >= 0; i--) {         int parent = i;         int child = 2 * parent + 1;         while (child < heapSize) {             if (child + 1 < heapSize                 && compare(heap[child], heap[child + 1])) {                 child++;             }             if (compare(heap[parent], heap[child])) {                 ppi temp = heap[parent];                 heap[parent] = heap[child];                 heap[child] = temp;                 parent = child;                 child = 2 * parent + 1;             }             else {                 break;             }         }     }       while (heapSize > 0) {         ppi top = heap[0];         for (i = 0; i < top.first; i++) {             ans[strlen(ans)] = top.second;         }           heap[0] = heap[heapSize - 1];         heapSize--;         int parent = 0;         int child = 2 * parent + 1;         while (child < heapSize) {             if (child + 1 < heapSize                 && compare(heap[child], heap[child + 1])) {                 child++;             }             if (compare(heap[parent], heap[child])) {                 ppi temp = heap[parent];                 heap[parent] = heap[child];                 heap[child] = temp;                 parent = child;                 child = 2 * parent + 1;             }             else {                 break;             }         }     }     free(arr);     free(heap);     free(mpp);     return ans; }   // Driver code int main() {     char str[] = "geeksforgeeks";       printf("%s\n", frequencySort(str));       return 0; }

## C++

 #include using namespace std;   //O(N*LogN) Time, O(Distinct(N)) Space //MIN HEAP Based - as we need less frequent element first #define ppi pair   //CUSTOM COMPARATOR for Heap class Compare{   public:   //Override   bool operator()(pairbelow, pair above){     if(below.first == above.first){       //freq same       return below.second > above.second; //lexicographically smaller is TOP     }     return below.first > above.first; //less freq at TOP   } };   string frequencySort(string s) {     unordered_map mpp;   priority_queue,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

## Java

 import java.util.*; class Pair implements Comparable {     int first;     char second;     Pair(int first,char second)     {         this.first  = first;         this.second  = second;     }     // Custom comparator useful for heap          public int compareTo(Pair a)     {        // If frequencies are same for two characters        // sort according to their order         if(this.first==a.first)             return this.second-a.second;          return this.first-a.first;     }     } class Main {     // O(N*LogN) Time, O(Distinct(N)) Space     public static String frequencySort(String s) {           // Creating a HashMap to store the frequency of characters         HashMap mpp = new HashMap();           // Creating a min heap to store the frequency and corresponding character         PriorityQueue min_heap = new PriorityQueue();           // Looping through the string to calculate the frequency of each character         for (char ch : s.toCharArray()) {             mpp.put(ch, mpp.getOrDefault(ch, 0) + 1);         }           // Adding the frequency and character to the min heap         for (char m : mpp.keySet()) {             min_heap.offer(new Pair(mpp.get(m), m));         }           String ans = "";         // Now we have in the TOP - Less Freq chars         while (!min_heap.isEmpty()) {             Pair pair = min_heap.poll();             int freq = pair.first;             char ch = pair.second;             // Append as many times of frequency             for (int i = 0; i < freq; i++) {                 ans += ch;             }         }         return ans;     }       // Driver code     public static void main(String[] args) {         String str = "geeksforgeeks";         System.out.println(frequencySort(str));     }   }

## Python3

 import heapq   # O(N*LogN) Time, O(Distinct(N)) Space def frequencySort(s):     mpp = {}     min_heap = []       for ch in s:         if ch in mpp:             mpp[ch] += 1         else:             mpp[ch] = 1       for m in mpp:         heapq.heappush(min_heap, (mpp[m], m)) # as freq is 1st , char is 2nd       ans = ""     #Now we have in the TOP - Less Freq chars     while min_heap:         freq, ch = heapq.heappop(min_heap)         ans += ch * freq # append as many times of freq     return ans   # Driver code if __name__ == '__main__':     str = "geeksforgeeks"     print(frequencySort(str))    # This code is contributed by Prince Kumar

## C#

 // C# approach using System; using System.Collections.Generic;   class Pair : IComparable {     public int first;     public char second;     public Pair(int first, char second)     {         this.first = first;         this.second = second;     }       // Custom comparator useful for heap     public int CompareTo(Pair a)     {         // If frequencies are same for two characters         // sort according to their order         if (this.first == a.first)             return this.second - a.second;         return this.first - a.first;     } } class Program {     // O(N*LogN) Time, O(Distinct(N)) Space     public static string frequencySort(string s)     {         // Creating a HashMap to store the frequency of         // characters         Dictionary mpp             = new Dictionary();           // Creating a min heap to store the frequency and         // corresponding character         SortedSet min_heap = new SortedSet();           // Looping through the string to calculate the         // frequency of each character         foreach(char ch in s.ToCharArray())         {             if (mpp.ContainsKey(ch))                 mpp[ch] = mpp[ch] + 1;             else                 mpp[ch] = 1;         }           // Adding the frequency and character to the min         // heap         foreach(char m in mpp.Keys)         {             min_heap.Add(new Pair(mpp[m], m));         }           string ans = "";         // Now we have in the TOP - Less Freq chars         while (min_heap.Count > 0) {             Pair pair = min_heap.Min;             int freq = pair.first;             char ch = pair.second;             // Append as many times of frequency             for (int i = 0; i < freq; i++) {                 ans += ch;             }             min_heap.Remove(pair);         }         return ans;     }       // Driver code     public static void Main(string[] args)     {         string str = "geeksforgeeks";         Console.WriteLine(frequencySort(str));     } }   // This code is contributed by Susobhan Akhuli

## Javascript

 // JavaScript approach class Pair {     constructor(first, second){         this.first = first;         this.second = second;     }     // Custom comparator useful for heap     compareTo(a)     {               // If frequencies are same for two characters     // sort according to their order         if(this.first === a.first){             return this.second - a.second;         }         return this.first - a.first;     } }   // O(N*LogN) Time, O(Distinct(N)) Space function frequencySort(s) {     // Creating a HashMap to store the frequency of characters     let mpp = new Map();       // Creating a min heap to store the frequency and corresponding character     let min_heap = [];       // Looping through the string to calculate the frequency of each character     for (let i = 0; i < s.length; i++) {         let ch = s.charAt(i);         let count = mpp.get(ch) || 0;         mpp.set(ch, count + 1);     }       // Adding the frequency and character to the min heap     for (let [key, value] of mpp.entries()) {         min_heap.push(new Pair(value, key));     }       min_heap.sort(function(a, b){ return a.compareTo(b); });       let ans = "";           // Now we have in the TOP - Less Freq chars     while (min_heap.length > 0) {         let pair = min_heap.shift();         let freq = pair.first;         let ch = pair.second;                   // Append as many times of frequency         for (let i = 0; i < freq; i++) {             ans += ch;         }     }     return ans; }   // Driver code let str = "geeksforgeeks"; console.log(frequencySort(str));   // This Code is Contributed by Susobhan Akhuli.

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)