Sort Characters By Frequency

Medium Heaps Top K / Kth Largest / Smallest Original on LeetCode

Sort Characters By Frequency is a medium heaps problem solved with the top k / kth largest / smallest pattern. The best approach, optimal (bucket sort by frequency), runs in O(n) time and O(n) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (sort every character with a frequency comparator) up.

Problem

Given a string s, rearrange its characters so that they are ordered by how often they appear, most frequent first. All copies of the same character must sit next to each other.

Upper and lower case letters count as different characters. If two characters appear the same number of times, either one may come first; any valid arrangement is accepted.

Examples

Example 1

Input
s = "banana"
Output
"aaannb"
Why
'a' appears 3 times, 'n' twice and 'b' once, so the a's come first, then the n's, then the b.

Example 2

Input
s = "xY7Y7Y"
Output
"YYY77x"
Why
'Y' appears 3 times and '7' twice. Upper and lower case letters are different characters.

Example 3

Input
s = "pqr"
Output
"pqr"
Why
Every character appears once, so any order of the three is accepted, for example "rqp".

Constraints

  • 1 <= s.length <= 5 * 10^5
  • s contains only English letters (upper and lower case) and digits.
  • When several characters share a frequency, any order between their groups is accepted.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 11 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (sort every character with a frequency comparator)O(n log n)O(n)
Max-heap of distinct charactersO(n + k log k)O(n + k)
Optimal (bucket sort by frequency)O(n)O(n)

1Brute force (sort every character with a frequency comparator)

TimeO(n log n)Sorting all n characters dominates.
SpaceO(n)The array of n characters being sorted.

Count each character, then sort all n characters by (count descending, character ascending). Ties are broken by the character so equal characters stay together.

  1. Count the frequency of each character.
  2. Put the n characters into an array and sort it by count descending, then by character.
  3. Join the sorted characters into the answer.
class Solution {
    public String frequencySort(String s) {
        int[] count = new int[128];
        for (char c : s.toCharArray()) count[c]++;
        Character[] chars = new Character[s.length()];
        for (int i = 0; i < s.length(); i++) chars[i] = s.charAt(i);
        Arrays.sort(chars, (a, b) -> count[a] != count[b] ? count[b] - count[a] : a - b);
        StringBuilder sb = new StringBuilder();
        for (char c : chars) sb.append(c);
        return sb.toString();
    }
}

2Max-heap of distinct characters

TimeO(n + k log k)Counting and writing are O(n); the heap holds k <= 62 distinct characters.
SpaceO(n + k)The heap has k entries and the output has n characters.

There are at most 62 distinct characters. Push each (character, count) pair into a max-heap ordered by count and pop them one by one, writing each character count times.

  1. Count the frequency of each character.
  2. Push every character that appears into a max-heap keyed by count (ties by character).
  3. Pop the heap; append the popped character count times.
class Solution {
    public String frequencySort(String s) {
        int[] count = new int[128];
        for (char c : s.toCharArray()) count[c]++;
        PriorityQueue<Character> heap = new PriorityQueue<>(
            (a, b) -> count[a] != count[b] ? count[b] - count[a] : a - b);
        for (char c = 0; c < 128; c++) {
            if (count[c] > 0) heap.offer(c);
        }
        StringBuilder sb = new StringBuilder();
        while (!heap.isEmpty()) {
            char c = heap.poll();
            for (int i = 0; i < count[c]; i++) sb.append(c);
        }
        return sb.toString();
    }
}

3Optimal (bucket sort by frequency)

TimeO(n)Counting, filling buckets and writing the output are each linear.
SpaceO(n)n + 1 buckets plus the output string.

A frequency is between 1 and n, so use n + 1 buckets: bucket f holds the characters that appear exactly f times. Walking the buckets from n down to 1 lists the characters by decreasing frequency without any comparison sort.

  1. Count the frequency of each character.
  2. Put each character into bucket[count].
  3. For f from n down to 1, append each character in bucket[f] exactly f times.
class Solution {
    public String frequencySort(String s) {
        int n = s.length();
        int[] count = new int[128];
        for (char c : s.toCharArray()) count[c]++;
        List<List<Character>> buckets = new ArrayList<>();
        for (int i = 0; i <= n; i++) buckets.add(new ArrayList<>());
        for (char c = 0; c < 128; c++) {
            if (count[c] > 0) buckets.get(count[c]).add(c);
        }
        StringBuilder sb = new StringBuilder();
        for (int f = n; f >= 1; f--) {
            for (char c : buckets.get(f)) {
                for (int i = 0; i < f; i++) sb.append(c);
            }
        }
        return sb.toString();
    }
}

Edge cases to test

  • A single character
  • All characters the same
  • Every character distinct (any permutation is valid)
  • 'A' and 'a' both present: they are counted separately

Hints

Hint 1

First count how often each character appears.

Hint 2

Each character must be written as one contiguous block, longest block first. How do you order the distinct characters by count?

Hint 3

A count is at most n. Can you put characters into buckets indexed by their count instead of sorting?

FAQ

What is the best time complexity for Sort Characters By Frequency?

Optimal (bucket sort by frequency) runs in O(n) time and O(n) extra space. Counting, filling buckets and writing the output are each linear.

Which pattern does Sort Characters By Frequency use?

It is a heaps problem that uses the top k / kth largest / smallest pattern. Other problems with the same pattern: Kth Largest Element in an Array, Kth Largest Element in a Stream, Top K Frequent Words.

Is there a brute force solution for Sort Characters By Frequency?

Yes. Brute force (sort every character with a frequency comparator) takes O(n log n) time and O(n) space. Count each character, then sort all n characters by (count descending, character ascending).

Which edge cases should I test for Sort Characters By Frequency?

A single character; All characters the same; Every character distinct (any permutation is valid); 'A' and 'a' both present: they are counted separately.