|
| 1 | +--- |
| 2 | +id: sort-characters-by-frequency |
| 3 | +title: Sort Characters By Frequency |
| 4 | +sidebar_label: 0451-Sort-Characters-By-Frequency |
| 5 | +tags: |
| 6 | +- Hash Table |
| 7 | +- String |
| 8 | +- Sorting |
| 9 | +- Heap (Priority Queue) |
| 10 | +description: "Given a string `s`, sort it in decreasing order based on the frequency of characters, and return the sorted string." |
| 11 | +--- |
| 12 | + |
| 13 | +## Problem |
| 14 | + |
| 15 | +Given a string `s`, sort it in decreasing order based on the frequency of characters, and return the sorted string. |
| 16 | + |
| 17 | +### Examples |
| 18 | + |
| 19 | +**Example 1:** |
| 20 | + |
| 21 | +**Input:** `s = "tree"` |
| 22 | +**Output:** `"eert"` |
| 23 | +**Explanation:** 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before 'r' and 't'. Therefore "eetr" is also a valid answer. |
| 24 | + |
| 25 | +**Example 2:** |
| 26 | + |
| 27 | +**Input:** `s = "cccaaa"` |
| 28 | +**Output:** `"cccaaa"` |
| 29 | +**Explanation:** Both 'c' and 'a' appear three times. So "aaaccc" is also a valid answer. Note that "cacaca" is incorrect, as same characters must be together. |
| 30 | + |
| 31 | +**Example 3:** |
| 32 | + |
| 33 | +**Input:** `s = "Aabb"` |
| 34 | +**Output:** `"bbAa"` |
| 35 | +**Explanation:** 'b' appears twice, 'A' and 'a' both appear once. Note that 'A' and 'a' are treated as two different characters. |
| 36 | + |
| 37 | +### Constraints |
| 38 | + |
| 39 | +- `1 <= s.length <= 5 * 10^5` |
| 40 | +- `s` consists of uppercase and lowercase English letters and digits. |
| 41 | + |
| 42 | +--- |
| 43 | + |
| 44 | +## Approach |
| 45 | + |
| 46 | +To solve this problem, we can follow these steps: |
| 47 | + |
| 48 | +1. **Count Frequencies:** Use a hash table (dictionary) to count the frequency of each character in the string. |
| 49 | +2. **Sort Characters:** Create a list of characters sorted by their frequency in descending order. |
| 50 | +3. **Build Result String:** Construct the result string by repeating characters based on their frequencies. |
| 51 | + |
| 52 | +### Steps: |
| 53 | + |
| 54 | +1. Create a hash table to store the frequency of each character. |
| 55 | +2. Sort the characters based on their frequency in descending order. |
| 56 | +3. Build the final string by appending each character multiplied by its frequency. |
| 57 | + |
| 58 | +### Solution |
| 59 | + |
| 60 | +#### Java Solution |
| 61 | + |
| 62 | +```java |
| 63 | +import java.util.HashMap; |
| 64 | +import java.util.Map; |
| 65 | +import java.util.PriorityQueue; |
| 66 | + |
| 67 | +class Solution { |
| 68 | + public String frequencySort(String s) { |
| 69 | + Map<Character, Integer> frequencyMap = new HashMap<>(); |
| 70 | + for (char c : s.toCharArray()) { |
| 71 | + frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1); |
| 72 | + } |
| 73 | + |
| 74 | + PriorityQueue<Character> maxHeap = new PriorityQueue<>((a, b) -> frequencyMap.get(b) - frequencyMap.get(a)); |
| 75 | + maxHeap.addAll(frequencyMap.keySet()); |
| 76 | + |
| 77 | + StringBuilder result = new StringBuilder(); |
| 78 | + while (!maxHeap.isEmpty()) { |
| 79 | + char c = maxHeap.poll(); |
| 80 | + int count = frequencyMap.get(c); |
| 81 | + for (int i = 0; i < count; i++) { |
| 82 | + result.append(c); |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + return result.toString(); |
| 87 | + } |
| 88 | +} |
| 89 | +``` |
| 90 | +### C++ Solution |
| 91 | + |
| 92 | +```cpp |
| 93 | +#include <unordered_map> |
| 94 | +#include <queue> |
| 95 | +#include <string> |
| 96 | + |
| 97 | +class Solution { |
| 98 | +public: |
| 99 | + string frequencySort(string s) { |
| 100 | + unordered_map<char, int> frequencyMap; |
| 101 | + for (char c : s) { |
| 102 | + frequencyMap[c]++; |
| 103 | + } |
| 104 | + |
| 105 | + priority_queue<pair<int, char>> maxHeap; |
| 106 | + for (auto& [c, freq] : frequencyMap) { |
| 107 | + maxHeap.push({freq, c}); |
| 108 | + } |
| 109 | + |
| 110 | + string result; |
| 111 | + while (!maxHeap.empty()) { |
| 112 | + auto [freq, c] = maxHeap.top(); |
| 113 | + maxHeap.pop(); |
| 114 | + result.append(freq, c); |
| 115 | + } |
| 116 | + |
| 117 | + return result; |
| 118 | + } |
| 119 | +}; |
| 120 | +``` |
| 121 | +
|
| 122 | +### Python Solution |
| 123 | +
|
| 124 | +```python |
| 125 | +from collections import Counter |
| 126 | +import heapq |
| 127 | +
|
| 128 | +class Solution: |
| 129 | + def frequencySort(self, s: str) -> str: |
| 130 | + frequency_map = Counter(s) |
| 131 | + max_heap = [(-freq, char) for char, freq in frequency_map.items()] |
| 132 | + heapq.heapify(max_heap) |
| 133 | + |
| 134 | + result = [] |
| 135 | + while max_heap: |
| 136 | + freq, char = heapq.heappop(max_heap) |
| 137 | + result.append(char * -freq) |
| 138 | + |
| 139 | + return ''.join(result) |
| 140 | +``` |
| 141 | +### Complexity Analysis |
| 142 | +**Time Complexity:** O(n log n) |
| 143 | +>Reason: Counting the frequency of each character takes O(n), and sorting the characters based on frequency takes O(n log n). |
| 144 | + |
| 145 | +**Space Complexity:** O(n) |
| 146 | +>Reason: The space needed for the frequency map, heap, and result string is proportional to the length of the input string. |
| 147 | +
|
| 148 | +### References |
| 149 | +LeetCode Problem: Sort Characters By Frequency |
0 commit comments