|
| 1 | +--- |
| 2 | +id: sort-characters-by-frequency |
| 3 | +title: Sort Characters By Frequency (LeetCode) |
| 4 | +sidebar_label: 0451-Sort Characters By Frequency |
| 5 | +tags: |
| 6 | + - Hash Table |
| 7 | + - String |
| 8 | + - Sorting |
| 9 | + - Heap(Priority Queue) |
| 10 | + - Bucket Sort |
| 11 | + - Counting |
| 12 | +description: 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. |
| 13 | +sidebar_position: 0451 |
| 14 | +--- |
| 15 | + |
| 16 | +## Problem Description |
| 17 | + |
| 18 | +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. |
| 19 | + |
| 20 | +Return the sorted string. If there are multiple answers, return any of them. |
| 21 | + |
| 22 | +Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces. |
| 23 | + |
| 24 | +### Example 1 |
| 25 | + |
| 26 | +- **Input:** ` s = "tree" ` |
| 27 | +- **Output:** `"eert"` |
| 28 | +- **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. |
| 29 | + |
| 30 | +### Example 2 |
| 31 | + |
| 32 | +- **Input:** ` s = "cccaaa" ` |
| 33 | +- **Output:** `"aaaccc"` |
| 34 | +- **Explanation:** Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers.Note that "cacaca" is incorrect, as the same characters must be together. |
| 35 | + |
| 36 | +### Example 3 |
| 37 | + |
| 38 | +- **Input:** ` s = "Aabb" ` |
| 39 | +- **Output:** `"bbAa"` |
| 40 | +- **Explanation:** "bbaA" is also a valid answer, but "Aabb" is incorrect.Note that 'A' and 'a' are treated as two different characters. |
| 41 | + |
| 42 | + |
| 43 | + |
| 44 | +### Constraints |
| 45 | + |
| 46 | +- `1 <= s.length <= 5 * 105` |
| 47 | +- `s consists of uppercase and lowercase English letters and digits.` |
| 48 | + |
| 49 | +## Approach |
| 50 | + |
| 51 | + - 1. Count the occurrences: We need to go through the string and count the occurrences of each character. This can be done efficiently by using a hash table or a counter data structure where each character is a key, and its count is the value. |
| 52 | + |
| 53 | + - 2. Sort based on counts: Once we have the counts, the next step is to sort the characters by these counts in descending order. We want the characters with higher counts to come first. |
| 54 | + |
| 55 | + - 3. With these counts, we can construct a new string. |
| 56 | + |
| 57 | + |
| 58 | + |
| 59 | +### Solution Code |
| 60 | + |
| 61 | +#### C++ |
| 62 | + |
| 63 | +```c++ |
| 64 | +class Solution { |
| 65 | +public: |
| 66 | + string frequencySort(string s) { |
| 67 | + unordered_map<char, int> frequencyMap; |
| 68 | + for (char ch : s) { |
| 69 | + ++frequencyMap[ch]; |
| 70 | + } |
| 71 | + vector<char> uniqueChars; |
| 72 | + for (auto& keyValue : frequencyMap) { |
| 73 | + uniqueChars.push_back(keyValue.first); |
| 74 | + } |
| 75 | + sort(uniqueChars.begin(), uniqueChars.end(), [&](char a, char b) { |
| 76 | + return frequencyMap[a] > frequencyMap[b]; |
| 77 | + }); |
| 78 | + string result; |
| 79 | + for (char ch : uniqueChars) { |
| 80 | + result += string(frequencyMap[ch], ch); |
| 81 | + } |
| 82 | + return result; |
| 83 | + } |
| 84 | +}; |
| 85 | + |
| 86 | +``` |
| 87 | +
|
| 88 | +#### java |
| 89 | +```java |
| 90 | +class Solution { |
| 91 | + public String frequencySort(String s) { |
| 92 | + Map<Character, Integer> frequencyMap = new HashMap<>(52); |
| 93 | + for (int i = 0; i < s.length(); ++i) { |
| 94 | + frequencyMap.merge(s.charAt(i), 1, Integer::sum); |
| 95 | + } |
| 96 | + List<Character> characters = new ArrayList<>(frequencyMap.keySet()); |
| 97 | + characters.sort((a, b) -> frequencyMap.get(b) - frequencyMap.get(a)); |
| 98 | + StringBuilder sortedString = new StringBuilder(); |
| 99 | + for (char c : characters) { |
| 100 | + for (int frequency = frequencyMap.get(c); frequency > 0; --frequency) { |
| 101 | + sortedString.append(c); |
| 102 | + } |
| 103 | + } |
| 104 | + return sortedString.toString(); |
| 105 | + } |
| 106 | +} |
| 107 | +
|
| 108 | +``` |
| 109 | + |
| 110 | +#### Python |
| 111 | +```python |
| 112 | +class Solution: |
| 113 | + def frequencySort(self, s: str) -> str: |
| 114 | + char_frequency = Counter(s) |
| 115 | + sorted_characters = sorted(char_frequency.items(), key=lambda item: -item[1]) |
| 116 | + frequency_sorted_string = ''.join(character * frequency for character, frequency in sorted_characters) |
| 117 | + return frequency_sorted_string |
| 118 | +``` |
| 119 | + |
| 120 | +#### Conclusion |
| 121 | +The above solutions use two-pointers approach to reverse the string. |
| 122 | + - 1. Time complexity: O(n logn) |
| 123 | + - 2. Space complexity: O(n) |
0 commit comments