15% off all plans & roadmaps Use code
See plansLeetCode 451 · Solution & editorial
Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.
Sort Characters By Frequency is a Heap (Priority Queue) Patterns problem, in the Top K Elements (Selection/Frequency) subpattern. The pattern covers top K elements, K-way merge, two heaps for median, and scheduling
Find top K elements using heap. Solve kth largest, top K frequent, and k closest points problems.
The reference solution runs in O(N) time and O(N) space.
Sort Characters By Frequency has been reported in interviews at Bloomberg, Amazon, Facebook.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Sort Characters By Frequency is a Heap (Priority Queue) Patterns problem, in the Top K Elements (Selection/Frequency) subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.