Sort Characters By Frequency

Rearrange a string so its most frequent characters come first, with all copies of each character kept together.

Given a string s, rearrange its characters so that a character that appears more often comes before one that appears less often. All copies of the same character must stand next to each other. Characters that appear equally often may come in either order, so any answer that follows these rules is accepted. Upper and lower case letters count as different characters.

Example 1
Input: s = "tree"
Output: "eert"
Explanation: e appears twice, t and r once each. "eetr" is also accepted.
Example 2
Input: s = "cccaaa"
Output: "cccaaa"
Explanation: c and a both appear three times, so "aaaccc" is also accepted. "cacaca" is not, because the copies of each letter are split up.
Example 3
Input: s = "Aabb"
Output: "bbAa"
Explanation: b appears twice. A and a are different characters with one copy each, so "bbaA" is also accepted.
Solution

The Idea

Imagine the string as a handful of letter tiles. To answer, you would sort the tiles into piles, one pile per character, and then lay the piles out in a row, the biggest pile first.

Take Example 1, "tree". The tiles are t, r, e and e, so the e pile has two tiles and the t and r piles have one each. The e pile goes first, then t and r in either order, which gives "eert" or "eetr". In Example 2 the c and a piles are the same size, so either can lead. What matters is that each pile is laid out whole: "cacaca" takes tiles from both piles in turn, and that is not allowed.

So the work splits in two: count how many copies each character has, then hand the characters out from the largest count down. How do we hand them out in that order? A heap is a structure built for exactly this: you add items, and it always gives back the one with the highest priority next. When the largest value comes out first, it is called a max-heap. Here the items are characters and the priority is each character's count.

Look at the picture below. It follows "tree" through the four boxes labelled 1 to 4.

The string tree is counted: t 1, r 1, e 2. A max-heap keeps the largest count on top, so e comes out first, then r and t. Writing each character as many times as its count gives ee + r + t = eert.

Box 1 is the string, with the two e tiles marked. Box 2, "count each character", gives t 1, r 1 and e 2. In box 3, the max-heap has e, with count 2, on top, so e is polled first, which means it is the first character taken out. Box 4 takes the characters from the top and writes each character as many times as its count: ee, then r, then t, which makes "eert".

Because each character is written in one go, all of its copies end up together without any extra check.

Solution Approach

Turning that idea into code means settling three things: how to count the characters, how to make the heap hand out the largest count first, and how to write the result so each character stays in one block.

Counting the characters

What should hold the counts? A HashMap<Character, Integer> from each character to its number of copies works for any character: lower case, upper case, digits or spaces. count.merge(c, 1, Integer::sum) stores 1 the first time c is seen and adds 1 to the stored count after that.

An array of 26 counts, indexed by c - 'a', only fits lower case letters. Example 3 already breaks it: 'A' - 'a' is -32, and counting "Aabb" that way throws ArrayIndexOutOfBoundsException: Index -32 out of bounds for length 26.

Making the heap hand out the largest count

Which Java class gives us a heap? PriorityQueue does, and on its own it is a min-heap: poll() returns the smallest item. We want the largest count first, so we pass a comparator that compares the counts in reverse:

Java
PriorityQueue<Character> heap =
        new PriorityQueue<>((a, b) -> count.get(b) - count.get(a));

The heap stores the characters themselves, and the comparator looks up their counts in the map. Taking b's count minus a's puts the character with the larger count first, which turns the queue into a max-heap. The subtraction cannot go past the range of an int here, because every count is between 1 and the length of the string. Characters with equal counts compare as equal, so the heap may return them in either order, which the problem allows.

Writing each character as one block

Why not simply sort the characters of the string by their counts? In "cacaca", c and a both have the count 3, so a sort that compares only counts sees all six characters as equal. Java's list sort keeps equal items in their original order, so sorting the characters that way returns "cacaca" unchanged.

Polling each distinct character once and appending it count.get(c) times avoids that problem. String.repeat builds the block, for example "e".repeat(2) gives "ee", and a StringBuilder joins the blocks together.

Skipping the heap (optional)

A count can only be a whole number from 1 to the length of the string. So instead of a heap, you could keep one list per possible count, put each character in the list for its count, and read the lists from the highest count down. That makes the ordering linear in the length of the string. When the string has only a few distinct characters, the heap holds only a few items, so the gain is small.

Java Solution

The method frequencySort works in these steps:

  1. First, count the characters: create the map count, then loop over the characters of s and call count.merge(c, 1, Integer::sum) for each one.
  2. Create heap, a PriorityQueue of characters with the comparator (a, b) -> count.get(b) - count.get(a), so it is a max-heap by count. Add every distinct character with heap.addAll(count.keySet()).
  3. Create a StringBuilder named sb. While heap is not empty, poll the character c with the largest count left and append it count.get(c) times with repeat.
  4. Once the heap is empty, every character has been written, so return sb.toString().

The main method runs the three examples, then "cacaca" with its copies split up, a string with digits, and the empty string, printed inside brackets so it can be seen.

Java
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

public class SortCharactersByFrequency {

    public static String frequencySort(String s) {
        Map<Character, Integer> count = new HashMap<>();
        for (char c : s.toCharArray()) {
            count.merge(c, 1, Integer::sum);           // 1 on first sight, else add 1
        }

        PriorityQueue<Character> heap =                // max-heap: largest count on top
                new PriorityQueue<>((a, b) -> count.get(b) - count.get(a));
        heap.addAll(count.keySet());

        StringBuilder sb = new StringBuilder();
        while (!heap.isEmpty()) {
            char c = heap.poll();                      // the most frequent character left
            sb.append(String.valueOf(c).repeat(count.get(c)));  // all copies of c together
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(frequencySort("tree"));
        System.out.println(frequencySort("cccaaa"));
        System.out.println(frequencySort("Aabb"));
        System.out.println(frequencySort("cacaca"));
        System.out.println(frequencySort("1a2b1a1"));
        System.out.println("[" + frequencySort("") + "]");
    }
}

Running it prints:

Output
eert
aaaccc
bbaA
aaaccc
111aab2
[]

"tree" gives eert, the answer from Example 1 and from the picture. For "cccaaa" the program prints aaaccc, not the cccaaa shown in Example 2. Both are accepted: c and a have the same count, so the heap is free to return either one first. "Aabb" gives bbaA for the same reason, since A and a have one copy each.

The fourth line shows the blocks at work: "cacaca" comes out as aaaccc, with each letter's copies together. In "1a2b1a1", the digit 1 appears three times and leads, then come the two a's, then b and 2 with one copy each. The map counts digits just like letters. The last line, [], is the empty string: nothing is counted, the heap stays empty, and the loop never runs.

Complexity

The work is one pass to count, one heap operation per distinct character, and one pass to write the result. Call the length of the string n and the number of distinct characters d.

  • Time: O(n + d log d), because counting and writing each touch the n characters once, while each of the d distinct characters is added to and polled from a heap of at most d items.
  • Space: O(n + d), because the StringBuilder grows to the full n characters, while the map and the heap hold one entry per distinct character.

Ranking items by how often they appear is also the heart of Top K Frequent Elements.