Sort Characters By Frequency
Max-heap of character counts
Count every character, then treat each (character, count) pair as a node in a max-heap ordered by count. Popping the root always gives the most frequent character left, so repeated pops in order build the answer directly.
Details
Animated on: Given a string, sort it in decreasing order based on the frequency of each character. s = "baedcbbbaeeeecc".
Problem:Sort Characters By FrequencyMedium
Max-heap of character counts
step 1 / 11
Count every character in "baedcbbbaeeeecc": b:4, a:2, e:5, d:1, c:3. Laid out as a complete binary tree in that order, it is not yet a valid max-heap.
1FUNCTION sortByFrequency(s):2 freq <- COUNT each character in s3 heap <- BUILD max-heap of (char, freq) pairs4 out <- EMPTY string5 WHILE heap is not empty:6 (c, f) <- EXTRACT-MAX(heap)7 APPEND c REPEATED f TIMES TO out8 RETURN out9END FUNCTION
← / → step · space play · Home restart
Every step in words
Show all 11 steps
- Count every character in "baedcbbbaeeeecc": b:4, a:2, e:5, d:1, c:3. Laid out as a complete binary tree in that order, it is not yet a valid max-heap.
- Heapify index 1: c:3 beats a:2 at index 1, so they swap. c:3 keeps sinking from index 4.
- Heapify index 0: e:5 beats b:4 at index 0, so they swap. e:5 keeps sinking from index 2.
- Every parent's frequency is now >= both its children's: e:5 >= c:3 >= b:4 >= d:1 >= a:2 down each path. The heap is built in O(n).
- b:4 beats a:2 at index 0, so they swap. b:4 keeps sinking from index 2.
- Pop the root, e:5 — append 'e' repeated 5 times: out = "eeeee". 4 characters left in the heap.
- c:3 beats d:1 at index 0, so they swap. c:3 keeps sinking from index 1.
- Pop the root, b:4 — append 'b' repeated 4 times: out = "eeeeebbbb". 3 characters left in the heap.
- Pop the root, c:3 — append 'c' repeated 3 times: out = "eeeeebbbbccc". 2 characters left in the heap.
- Pop the root, a:2 — append 'a' repeated 2 times: out = "eeeeebbbbcccaa". 1 character left in the heap.
- Pop the root, d:1 — append 'd' repeated 1 time: out = "eeeeebbbbcccaad". Heap is empty; done.
Now solve it yourself
Watching is the first half. The second is writing it without the animation.