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
Example 1
Output: "eert"
Explanation: e appears twice, t and r once each. "eetr" is also accepted.
Example 2
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
Output: "bbAa"
Explanation: b appears twice. A and a are different characters with one copy each, so "bbaA" is also accepted.
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""eert""eetr""cacaca"
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"
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>count.merge(c, 1, Integer::sum)c
An array of 26 counts, indexed by c - 'a''A' - 'a'"Aabb"ArrayIndexOutOfBoundsException: Index -32 out of bounds for length 26
Making the heap hand out the largest count
Which Java class gives us a heap? PriorityQueuepoll()
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 baint
Writing each character as one block
Why not simply sort the characters of the string by their counts? In "cacaca""cacaca"
Polling each distinct character once and appending it count.get(c)String.repeat"e".repeat(2)"ee"StringBuilder
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
- First, count the characters: create the map
, then loop over the characters ofcount and calls for each one.count.merge(c, 1, Integer::sum) - Create
, aheap of characters with the comparatorPriorityQueue , so it is a max-heap by count. Add every distinct character with(a, b) -> count.get(b) - count.get(a) .heap.addAll(count.keySet()) - Create a
namedStringBuilder . Whilesb is not empty, poll the characterheap with the largest count left and append itc times withcount.get(c) .repeat - Once the heap is empty, every character has been written, so return
.sb.toString()
The main"cacaca"
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:
eert
aaaccc
bbaA
aaaccc
111aab2
[]
"tree"eert"cccaaa"aaaccccccaaa"Aabb"bbaA
The fourth line shows the blocks at work: "cacaca"aaaccc"1a2b1a1"[]
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
grows to the full n characters, while the map and the heap hold one entry per distinct character.StringBuilder
Ranking items by how often they appear is also the heart of