> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/top-k-elements-heap-bucket-sort/451.-sort-characters-by-frequency.md).

# 451. Sort Characters By Frequency

{% embed url="<https://leetcode.com/problems/sort-characters-by-frequency/>" %}

### 1. use maxHeap,&#x20;

#### O(nlogm), m is the 26 char, so it's O(n),  O(n)

```java
class Solution {
    public String frequencySort(String s) {
        Map<Character, Integer> map = new HashMap<>();
        for (char c : s.toCharArray()) {
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        
        PriorityQueue<Character> maxHeap = new PriorityQueue<>((a, b) -> map.get(b) - map.get(a));
        maxHeap.addAll(map.keySet());
        
        StringBuilder sb = new StringBuilder();
        
        while (maxHeap.size() > 0) {
            char key = maxHeap.remove();
            for (int i = 0; i < map.get(key); i++) {
                sb.append(key);
            }
        }
        return sb.toString();
    }
}
```

### 2. use bucket sort

O(n), O(n)<br>

```java
// bucket 都會存 freq 在 array index (list array
// 所以大小都要宣告比 input 
List<Character> bucket[] = new List[s.length() + 1];


// 之後依 bucket 尾巴開始取出, 因為有可能有些 freq index下
// 有些會沒資料 所以要判斷 null
for (int i = bucket.length - 1; i >= 0; i--) {
            if (bucket[i] != null) {


// 不是 null 的 list, 就可以開始把某freq的值取出
for (char c : bucket[i]) {
        for (int fr = 0; fr < i; fr++) { // 還要按數量印出
            sb.append(c);
        }
    }
```

```java
class Solution {
    public String frequencySort(String s) {
        Map<Character, Integer> map = new HashMap<>();
        for (char c : s.toCharArray()) {
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        
        List<Character> bucket[] = new List[s.length() + 1];
        for (char c : map.keySet()) {
            int freq = map.get(c);
            if (bucket[freq] == null) {
                bucket[freq] = new ArrayList<>();
            }
            bucket[freq].add(c);
        }
        
        
        StringBuilder sb = new StringBuilder();
        for (int i = bucket.length - 1; i >= 0; i--) {
            if (bucket[i] != null) {
                for (char c : bucket[i]) {
                    for (int fr = 0; fr < i; fr++) {
                        sb.append(c);
                    }
                }
            }
        }
        return sb.toString();
        
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/top-k-elements-heap-bucket-sort/451.-sort-characters-by-frequency.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
