451 Sort Characters By Frequency

1. Question

Given a string, sort it in decreasing order based on the frequency of characters.

Example 1:

Input: "tree"

Output: "eert"

Explanation:
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.

Example 2:

Input: "cccaaa"

Output: "cccaaa"

Explanation:
Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
Note that "cacaca" is incorrect, as the same characters must be together.

Example 3:

2. Implementation

(1) Bucket Sort

(2) Heap

3. Time & Space Complexity

Bucket Sort: 时间复杂度O(n), 空间复杂度O(n)

Heap: 时间复杂度O(n), 空间复杂度O(n)

Last updated

Was this helpful?