Sort Characters By Frequency — LeetCode 451 Python Solution
MediumHash TableStringBucket SortCountingSortingHeap (Priority Queue)
- Problem
- #451
- Pattern
- Heap / Priority Queue
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- s = "tree"
- Output
- "eert"
- Explanation
- 'e' appears twice while 'r' and 't' both appear once.
Python solution
Python
class Solution:
def frequencySort(self, s: str) -> str:
cnt = Counter(s)
return ''.join(c * v for c, v in sorted(cnt.items(), key=lambda x: -x[1]))Complexity
| Measure | Complexity |
|---|---|
| Time | O(n + k \times \log k) |
| Space | O(n + k), where n is the length of the string s, and k is the number of distinct characters auxiliary |
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 451. Sort Characters By Frequency is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.
The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 451. Sort Characters By Frequency?
- LeetCode 451. Sort Characters By Frequency is rated Medium on LeetCode.
- What is the time complexity of LeetCode 451. Sort Characters By Frequency?
- The Python solution on this page runs in O(n + k \times \log k).
- What is the space complexity of LeetCode 451. Sort Characters By Frequency?
- The Python solution on this page uses O(n + k), where n is the length of the string s, and k is the number of distinct characters auxiliary space.
- What topics does LeetCode 451. Sort Characters By Frequency cover?
- LeetCode 451. Sort Characters By Frequency is tagged Hash Table, String, Bucket Sort, Counting, Sorting and Heap (Priority Queue) on LeetCode.