Open In App

Sort a string according to the frequency of characters

Last Updated : 07 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string s consisting of lowercase and/or uppercase English letters, return a new string where the characters are sorted in increasing order of their frequency. If two characters have the same frequency, they should be sorted in lexicographical order (i.e., based on ASCII value).
Each character should appear in the output string exactly as many times as it appears in the input.
Examples: 

Input: s = "geeksforgeeks"
Output: "forggkksseeee"
Explanation: Frequencies: e=4, g=2, k=2, s=2, f=1, o=1, r=1. Characters are sorted by increasing frequency, and lexicographically if equal.

Input: s = "abc"
Output: "abc"
Explanation: All characters occur once, so they are returned in lexicographical order.

[Naive Approach] Sorting the Pair of character and frequency - O(n^2) Time and O(n) Space

The idea is to sort the characters of the string based on how frequently they appear. For each character, we count its total frequency in the string and pair it with the character. These (frequency, character) pairs are then sorted in increasing order of frequency. Finally, we rebuild the string using the sorted characters to get the desired output.

Step-By-Step Approach:

  • Traverse the string: For each character s[i], count how many times it appears in the entire string using a helper function countFrequency.
  • Store pairs: Store each character with its frequency in an array of structs or a list of pairs.
  • Sort by frequency: Use a sorting function (like sort() in C++/Java/Python or qsort() in C) to sort the array/list based on the frequency value.
  • Build result: Concatenate characters from the sorted list to form the final output string.
C++
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

// returns count of a character in the string
int countFrequency(string &s, char ch) {
    int count = 0;

    for (int i = 0; i < s.length(); i++) {
        // check if current character matches ch
        if (s[i] == ch)
            ++count;
    }

    return count;
}

// function to sort the string according to frequency
string frequencySort(string &s) {
    int n = s.length();

    // vector to store frequency with corresponding character
    vector<pair<int, char>> vp;

    // insert frequency and character into the vector
    for (int i = 0; i < n; i++) {
        vp.push_back(make_pair(countFrequency(s, s[i]), s[i]));
    }

    // sort the vector by frequency (pair first value)
    sort(vp.begin(), vp.end());

    // build the final answer string
    string ans = "";
    for (int i = 0; i < vp.size(); i++)
        ans += vp[i].second;

    return ans;
}

int main() {
    string s = "geeksforgeeks";

    string ans = frequencySort(s);
    cout << ans << endl;
    return 0;
}
C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

// structure to hold frequency and character
typedef struct {
    int freq;
    char ch;
} CharFreq;

// returns count of a character in the string
int countFrequency(char s[], char ch) {
    int count = 0;
    int len = strlen(s);

    for (int i = 0; i < len; i++) {
        // check if current character matches ch
        if (s[i] == ch)
            ++count;
    }

    return count;
}

// comparator function for qsort
int compare(const void *a, const void *b) {
    CharFreq *x = (CharFreq *)a;
    CharFreq *y = (CharFreq *)b;
    return x->freq - y->freq;
}

// function to sort the string according to frequency
void frequencySort(char s[], char ans[]) {
    int n = strlen(s);

    // array to store frequency and corresponding character
    CharFreq arr[100];  // assume max length <= 100

    // insert frequency and character into the array
    for (int i = 0; i < n; i++) {
        arr[i].freq = countFrequency(s, s[i]);
        arr[i].ch = s[i];
    }

    // sort the array by frequency
    qsort(arr, n, sizeof(CharFreq), compare);

    // build the final answer string
    for (int i = 0; i < n; i++) {
        ans[i] = arr[i].ch;
    }
    ans[n] = '\0';  // null-terminate the result
}

int main() {
    char s[] = "geeksforgeeks";
    char ans[100];

    frequencySort(s, ans);
    printf("%s\n", ans);

    return 0;
}
Java
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

class GfG {

    // returns count of a character in the string
    static int countFrequency(String s, char ch) {
        int count = 0;

        for (int i = 0; i < s.length(); i++) {
            // check if current character matches ch
            if (s.charAt(i) == ch)
                ++count;
        }

        return count;
    }

    // function to sort the string according to frequency
    static String frequencySort(String s) {
        int n = s.length();

        // list to store frequency with corresponding character (as ASCII)
        List<List<Integer>> vp = new ArrayList<>();

        // insert frequency and character into the list
        for (int i = 0; i < n; i++) {
            List<Integer> temp = new ArrayList<>();
            temp.add(countFrequency(s, s.charAt(i)));   // frequency
            temp.add((int) s.charAt(i));                // character ASCII
            vp.add(temp);
        }

        // sort the list by frequency (first value)
        Collections.sort(vp, new Comparator<List<Integer>>() {
            public int compare(List<Integer> a, List<Integer> b) {
                return a.get(0) - b.get(0);
            }
        });

        // build the final answer string
        StringBuilder ans = new StringBuilder();
        for (List<Integer> entry : vp) {
            ans.append((char)(int) entry.get(1));
        }

        return ans.toString();
    }

    public static void main(String[] args) {
        String s = "geeksforgeeks";

        String ans = frequencySort(s);
        System.out.println(ans);
    }
}
Python
# returns count of a character in the string
def countFrequency(s, ch):
    count = 0
    for i in range(len(s)):
        # check if current character matches ch
        if s[i] == ch:
            count += 1
    return count

# function to sort the string according to frequency
def frequencySort(s):
    n = len(s)

    # list to store frequency with corresponding character
    vp = []

    # insert frequency and character into the list
    for i in range(n):
        vp.append((countFrequency(s, s[i]), s[i]))

    # sort the list by frequency (pair first value)
    vp.sort()

    # build the final answer string
    ans = ""
    for freq, ch in vp:
        ans += ch

    return ans

if __name__ == "__main__":
    s = "geeksforgeeks"
    ans = frequencySort(s)
    print(ans)
C#
using System;
using System.Collections.Generic;

class GfG {

    // returns count of a character in the string
    static int countFrequency(string s, char ch) {
        int count = 0;

        for (int i = 0; i < s.Length; i++) {
            // check if current character matches ch
            if (s[i] == ch)
                ++count;
        }

        return count;
    }

    // function to sort the string according to frequency
    static string frequencySort(string s) {
        int n = s.Length;

        // list to store frequency with corresponding character
        List<(int, char)> vp = new List<(int, char)>();

        // insert frequency and character into the list
        for (int i = 0; i < n; i++) {
            vp.Add((countFrequency(s, s[i]), s[i]));
        }

        // sort the list by frequency (pair first value)
        vp.Sort((a, b) => a.Item1.CompareTo(b.Item1));

        // build the final answer string
        string ans = "";
        foreach (var p in vp)
            ans += p.Item2;

        return ans;
    }

    static void Main(string[] args) {
        string s = "geeksforgeeks";

        string ans = frequencySort(s);
        Console.WriteLine(ans);
    }
}
JavaScript
// returns count of a character in the string
function countFrequency(s, ch) {
    let count = 0;

    for (let i = 0; i < s.length; i++) {
        // check if current character matches ch
        if (s[i] === ch)
            count++;
    }

    return count;
}

// function to sort the string according to frequency
function frequencySort(s) {
    let n = s.length;

    // array to store frequency with corresponding character
    let vp = [];

    // insert frequency and character into the array
    for (let i = 0; i < n; i++) {
        vp.push([countFrequency(s, s[i]), s[i]]);
    }

    // sort the array by frequency (pair first value)
    vp.sort((a, b) => a[0] - b[0]);

    // build the final answer string
    let ans = "";
    for (let i = 0; i < vp.length; i++)
        ans += vp[i][1];

    return ans;
}

// Driver Code
let s = "geeksforgeeks";
let ans = frequencySort(s);
console.log(ans);

Output
forggkksseeee

[Expected Approach 1] Frequency Counting + Custom Sorting

The idea is to first count the frequency of each character using a fixed-size array (since we assume lowercase letters only). We then create a vector of (frequency, character) pairs and sort it in increasing order of frequency. Finally, we rebuild the original string by placing each character according to its frequency in the sorted order.

C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
  public:
    // function to sort the string according to frequency
    string frequencySort(string &s) {
        int n = s.size();

        // array to store frequency of lowercase letters
        vector<int> fre(26, 0);
        for (int i = 0; i < n; i++) {
            fre[s[i] - 'a']++;
        }

        // vector to store (frequency, character) pairs
        vector<pair<int, char>> vec;
        for (int i = 0; i < 26; i++) {
            if (fre[i] != 0)
                vec.push_back({fre[i], i + 'a'});
        }

        // sort the vector by frequency (ascending)
        sort(vec.begin(), vec.end());

        // rebuild the string
        int idx = 0;
        for (auto it : vec) {
            int cnt = it.first;
            while (cnt--) {
                s[idx++] = it.second;
            }
        }

        return s;
    }
};

int main() {
    string s = "geeksforgeeks";
    Solution obj;
    string ans = obj.frequencySort(s);
    cout << ans << endl;
    return 0;
}
C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

// structure to hold frequency and character
typedef struct {
    int freq;
    char ch;
} CharFreq;

// comparator for sorting by frequency
int compare(const void* a, const void* b) {
    CharFreq* x = (CharFreq*)a;
    CharFreq* y = (CharFreq*)b;
    return x->freq - y->freq;
}

// function to sort the string according to frequency
void frequencySort(char s[]) {
    int n = strlen(s);

    // array to store frequency of lowercase letters
    int fre[26] = {0};
    for (int i = 0; i < n; i++) {
        fre[s[i] - 'a']++;
    }

    // create frequency-character array
    CharFreq vec[26];
    int size = 0;
    for (int i = 0; i < 26; i++) {
        if (fre[i] > 0) {
            vec[size].freq = fre[i];
            vec[size].ch = i + 'a';
            size++;
        }
    }

    // sort the array by frequency
    qsort(vec, size, sizeof(CharFreq), compare);

    // rebuild the string
    int idx = 0;
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < vec[i].freq; j++) {
            s[idx++] = vec[i].ch;
        }
    }
    s[idx] = '\0';  // null-terminate
}

int main() {
    char s[] = "geeksforgeeks";
    frequencySort(s);
    printf("%s\n", s);
    return 0;
}
Java
import java.util.Collections;
import java.util.ArrayList;
import java.util.List;

class GfG {

    // function to sort the string according to frequency
    static String frequencySort(String s) {
        int n = s.length();

        // array to store frequency of lowercase letters
        int[] fre = new int[26];
        for (int i = 0; i < n; i++) {
            fre[s.charAt(i) - 'a']++;
        }

        // list to store (frequency, character)
        List<int[]> vec = new ArrayList<>();
        for (int i = 0; i < 26; i++) {
            if (fre[i] > 0) {
                vec.add(new int[]{fre[i], i});
            }
        }

        // sort the list by frequency
        Collections.sort(vec, (a, b) -> a[0] - b[0]);

        // rebuild the string
        StringBuilder ans = new StringBuilder();
        for (int[] pair : vec) {
            for (int i = 0; i < pair[0]; i++) {
                ans.append((char) (pair[1] + 'a'));
            }
        }

        return ans.toString();
    }

    public static void main(String[] args) {
        String s = "geeksforgeeks";
        String ans = frequencySort(s);
        System.out.println(ans);
    }
}
Python
# function to sort the string according to frequency
def frequencySort(s):
    n = len(s)

    # array to store frequency of lowercase letters
    fre = [0] * 26
    for ch in s:
        fre[ord(ch) - ord('a')] += 1

    # list to store (frequency, character)
    vec = []
    for i in range(26):
        if fre[i] > 0:
            vec.append((fre[i], chr(i + ord('a'))))

    # sort the list by frequency
    vec.sort()

    # rebuild the string
    ans = ""
    for freq, ch in vec:
        ans += ch * freq

    return ans

if __name__ == "__main__":
    s = "geeksforgeeks"
    ans = frequencySort(s)
    print(ans)
C#
using System;
using System.Collections.Generic;

class GfG {

    // function to sort the string according to frequency
    static string frequencySort(string s) {
        int n = s.Length;

        // array to store frequency of lowercase letters
        int[] fre = new int[26];
        for (int i = 0; i < n; i++) {
            fre[s[i] - 'a']++;
        }

        // list to store (frequency, character index)
        List<(int, int)> vec = new List<(int, int)>();
        for (int i = 0; i < 26; i++) {
            if (fre[i] > 0) {
                vec.Add((fre[i], i));
            }
        }

        // sort the list by frequency
        vec.Sort((a, b) => a.Item1.CompareTo(b.Item1));

        // rebuild the string
        string ans = "";
        foreach (var pair in vec) {
            ans += new string((char)(pair.Item2 + 'a'), pair.Item1);
        }

        return ans;
    }

    static void Main(string[] args) {
        string s = "geeksforgeeks";
        string ans = frequencySort(s);
        Console.WriteLine(ans);
    }
}
JavaScript
// function to sort the string according to frequency
function frequencySort(s) {
    let n = s.length;

    // array to store frequency of lowercase letters
    let fre = new Array(26).fill(0);
    for (let i = 0; i < n; i++) {
        fre[s.charCodeAt(i) - 97]++;
    }

    // array to store (frequency, character index)
    let vec = [];
    for (let i = 0; i < 26; i++) {
        if (fre[i] > 0) {
            vec.push([fre[i], i]);
        }
    }

    // sort the array by frequency
    vec.sort((a, b) => a[0] - b[0]);

    // rebuild the string
    let ans = "";
    for (let [freq, idx] of vec) {
        ans += String.fromCharCode(idx + 97).repeat(freq);
    }

    return ans;
}

// Driver Code
let s = "geeksforgeeks";
let ans = frequencySort(s);
console.log(ans);

Output
forggkksseeee

Time Complexity: O(n + k log k), the frequency of each character is counted in O(n) time, where n is the length of the string. After that, we sort at most k = 26 unique lowercase letters based on their frequency, which takes O(k log k) time. Since k is constant (26), the overall complexity simplifies to O(n) in practice.
Auxiliary Space: O(k), an extra array of size 26 is used to store the frequency of lowercase letters, and a temporary list or array of up to 26 elements is created for sorting. Therefore, the auxiliary space is O(k), which is O(1) in practice because the alphabet size is fixed.

[Expected Approach 2] Using Mean Heap

The idea is to count the frequency of each character in the given string using a hash map. Then, insert each character along with its frequency into a min-heap (priority queue or sorted structure) so that characters with lower frequency come first. After building the heap, we repeatedly extract the minimum frequency character and append it to the result string as many times as its frequency. This results in sorting characters based on their frequency in ascending order.

Step-By-Step Approach:

  • First, we iterate through the string and count the frequency of each character using a hash map or dictionary.
  • Then, for each character-frequency pair, we push it into a min-heap where the element with the lowest frequency comes at the top. If two characters have the same frequency, the one with the lower ASCII value is prioritized.
  • Finally, we repeatedly extract the top of the heap and append the character to the result string as many times as its frequency, until the heap is empty.
C++
#include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
#include <string>
using namespace std;

// Custom comparator for min-heap
class Compare {
  public:
    bool operator()(vector<int>& below, vector<int>& above) {
        // if frequency is the same, compare by character
        if (below[0] == above[0]) {
            return below[1] > above[1];
        }
        // else compare by frequency
        return below[0] > above[0];
    }
};

// function to sort characters by frequency (ascending)
string frequencySort(string &s) {

    // map to store frequency of each character
    unordered_map<char, int> freqMap;
    for (char ch : s) {
        freqMap[ch]++;
    }

    // min-heap to store {frequency, character ASCII}
    priority_queue<vector<int>, vector<vector<int>>, Compare> minHeap;

    for (auto it : freqMap) {
        minHeap.push({it.second, (int)it.first});
    }

    // build the final answer string
    string ans = "";

    while (!minHeap.empty()) {
        int freq = minHeap.top()[0];
        char ch = (char)minHeap.top()[1];

        // append character freq number of times
        ans.append(freq, ch);

        minHeap.pop();
    }

    return ans;
}

int main() {
    string s = "geeksforgeeks";

    cout << frequencySort(s) << "\n";

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_CHAR 256

// structure to store frequency and character ASCII
typedef struct {
    int freq;
    int ch;
} CharFreq;

// function to swap two CharFreq elements
void swap(CharFreq* a, CharFreq* b) {
    CharFreq temp = *a;
    *a = *b;
    *b = temp;
}

// function to maintain min-heap property
void heapify(CharFreq heap[], int n, int i) {
    int smallest = i;
    int l = 2*i + 1;
    int r = 2*i + 2;

    // if frequency is same, use ASCII comparison
    if (l < n && (heap[l].freq < heap[smallest].freq ||
       (heap[l].freq == heap[smallest].freq && heap[l].ch < heap[smallest].ch))) {
        smallest = l;
    }

    if (r < n && (heap[r].freq < heap[smallest].freq ||
       (heap[r].freq == heap[smallest].freq && heap[r].ch < heap[smallest].ch))) {
        smallest = r;
    }

    if (smallest != i) {
        swap(&heap[i], &heap[smallest]);
        heapify(heap, n, smallest);
    }
}

// function to build a min-heap
void buildMinHeap(CharFreq heap[], int n) {
    for (int i = n/2 - 1; i >= 0; i--) {
        heapify(heap, n, i);
    }
}

// function to extract the min element from heap
CharFreq extractMin(CharFreq heap[], int* heapSize) {
    CharFreq min = heap[0];
    heap[0] = heap[*heapSize - 1];
    (*heapSize)--;
    heapify(heap, *heapSize, 0);
    return min;
}

// function to sort characters by frequency (ascending)
char* frequencySort(char* s) {
    int freqMap[MAX_CHAR] = {0};

    // count frequency
    for (int i = 0; s[i]; i++) {
        freqMap[(int)s[i]]++;
    }

    CharFreq heap[MAX_CHAR];
    int heapSize = 0;

    // fill heap array with non-zero frequency characters
    for (int i = 0; i < MAX_CHAR; i++) {
        if (freqMap[i]) {
            heap[heapSize].freq = freqMap[i];
            heap[heapSize].ch = i;
            heapSize++;
        }
    }

    // build the min-heap
    buildMinHeap(heap, heapSize);

    // create result string
    char* ans = (char*)malloc(strlen(s) + 1);
    int idx = 0;

    while (heapSize > 0) {
        CharFreq curr = extractMin(heap, &heapSize);
        for (int i = 0; i < curr.freq; i++) {
            ans[idx++] = (char)curr.ch;
        }
    }

    ans[idx] = '\0';
    return ans;
}

int main() {
    char s[] = "geeksforgeeks";
    char* res = frequencySort(s);
    printf("%s\n", res);
    free(res);
    return 0;
}
Java
import java.util.PriorityQueue;
import java.util.HashMap;
import java.util.Map;
import java.util.Comparator;

class GfG {

    // class to represent [frequency, character ASCII]
    static class CharFreq {
        int freq;
        int ch;

        CharFreq(int freq, int ch) {
            this.freq = freq;
            this.ch = ch;
        }
    }

    // Custom comparator for PriorityQueue
    static class Compare implements Comparator<CharFreq> {
        public int compare(CharFreq a, CharFreq b) {
            // if frequency is the same, compare by character
            if (a.freq == b.freq) {
                return a.ch - b.ch;
            }
            // else compare by frequency
            return a.freq - b.freq;
        }
    }

    // function to sort characters by frequency (ascending)
    static String frequencySort(String s) {
        Map<Character, Integer> freqMap = new HashMap<>();
        for (char ch : s.toCharArray()) {
            freqMap.put(ch, freqMap.getOrDefault(ch, 0) + 1);
        }

        PriorityQueue<CharFreq> minHeap = new PriorityQueue<>(new Compare());

        for (Map.Entry<Character, Integer> entry : freqMap.entrySet()) {
            minHeap.add(new CharFreq(entry.getValue(), (int) entry.getKey()));
        }

        StringBuilder ans = new StringBuilder();

        while (!minHeap.isEmpty()) {
            CharFreq top = minHeap.poll();
            for (int i = 0; i < top.freq; i++) {
                ans.append((char) top.ch);
            }
        }

        return ans.toString();
    }

    public static void main(String[] args) {
        String s = "geeksforgeeks";
        System.out.println(frequencySort(s));
    }
}
Python
import heapq

# function to sort characters by frequency
def frequencySort(s):
    freq = [0] * 128

    for ch in s:
        freq[ord(ch)] += 1

    minH = []

    for i in range(128):
        if freq[i] > 0:
            heapq.heappush(minH, [freq[i], chr(i)])

    ans = ""
    while minH:
        count, ch = heapq.heappop(minH)
        ans += ch * count

    return ans

if __name__ == "__main__":
    s = "geeksforgeeks"
    print(frequencySort(s))
C#
using System;
using System.Collections.Generic;

class Pair : IComparable<Pair> {
    public int first;     // frequency
    public char second;   // character

    public Pair(int first, char second) {
        this.first = first;
        this.second = second;
    }

    // Custom comparator useful for SortedSet
    public int CompareTo(Pair other) {
        // If frequencies are same, compare characters
        if (this.first == other.first) {
            if (this.second == other.second)
                return 0;
            return this.second - other.second;
        }
        return this.first - other.first;
    }

    // Override Equals and GetHashCode for correctness in SortedSet
    public override bool Equals(object obj) {
        if (obj == null || GetType() != obj.GetType()) return false;
        Pair p = (Pair)obj;
        return this.first == p.first && this.second == p.second;
    }

    public override int GetHashCode() {
        return first.GetHashCode() ^ second.GetHashCode();
    }
}

class Program {

    // function to sort characters by frequency (ascending)
    public static string frequencySort(string s) {

        // map to store frequency of each character
        Dictionary<char, int> mpp = new Dictionary<char, int>();

        // calculate frequency
        foreach (char ch in s.ToCharArray()) {
            if (mpp.ContainsKey(ch))
                mpp[ch]++;
            else
                mpp[ch] = 1;
        }

        // min-heap using SortedSet
        SortedSet<Pair> minHeap = new SortedSet<Pair>();

        foreach (char ch in mpp.Keys) {
            minHeap.Add(new Pair(mpp[ch], ch));
        }

        string ans = "";

        // build final answer
        while (minHeap.Count > 0) {
            Pair top = minHeap.Min;
            for (int i = 0; i < top.first; i++) {
                ans += top.second;
            }
            minHeap.Remove(top);
        }

        return ans;
    }

    // Driver code
    public static void Main(string[] args) {
        string str = "geeksforgeeks";
        Console.WriteLine(frequencySort(str));
    }
}
JavaScript
// function to sort characters by frequency (ascending)
function frequencySort(s) {

    // map to store frequency of each character
    let freqMap = {};
    for (let ch of s) {
        freqMap[ch] = (freqMap[ch] || 0) + 1;
    }

    // create an array of [frequency, ASCII] pairs
    let heap = [];
    for (let ch in freqMap) {
        heap.push([freqMap[ch], ch.charCodeAt(0)]);
    }

    // sort using custom comparator
    heap.sort((a, b) => {
        if (a[0] === b[0]) return a[1] - b[1];
        return a[0] - b[0];
    });

    let ans = "";

    for (let [freq, ascii] of heap) {
        let ch = String.fromCharCode(ascii);
        ans += ch.repeat(freq);
    }

    return ans;
}

// Driver Code
let s = "geeksforgeeks";
console.log(frequencySort(s));

Output
forggkksseeee

Time Complexity: O(n ×  log k), Here, n is the length of the input string and k is the number of distinct characters. We first traverse the string in O(n) to build the frequency map. Then, we insert k elements into the min-heap, each taking O(log k) time. Lastly, extracting and appending also takes O(k log k) in total.

Auxiliary Space: O(k), We use extra space for the frequency map and the heap, both storing up to k entries where k is the number of distinct characters.


Similar Reads