← Home

451. Sort Characters By Frequency

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
greedyC++Markdown
451

This is one of those problems where the clean idea matters more than the amount of code. For 451. Sort Characters By Frequency, the solution in this repository is mainly a greedy solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: greedy.

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are frequencySort, buckets.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 592 ms, faster than 5.01% of C++ online submissions for Sort Characters By Frequency.
02//Memory Usage: 8.3 MB, less than 100.00% of C++ online submissions for Sort Characters By Frequency.
03class Solution {
04public:
05    string frequencySort(string s) {
06        unordered_map<char, int> counter;
07        
08        for(char c : s){
09            counter[c]++;
10        }
11        
12        sort(s.begin(), s.end(), 
13            [&counter](const char a, const char b){
14                return (counter[a] == counter[b]) ? a < b : counter[a] > counter[b];
15            });
16        
17        return s;
18    }
19};
20
21//bucket sort, O(n) time
22//Runtime: 64 ms, faster than 19.59% of C++ online submissions for Sort Characters By Frequency.
23//Memory Usage: 16.5 MB, less than 17.65% of C++ online submissions for Sort Characters By Frequency.
24class Solution {
25public:
26    string frequencySort(string s) {
27        unordered_map<char, int> counter;
28        
29        for(char c : s){
30            counter[c]++;
31        }
32        
33        /*
34        reserve the space
35        the count of a char(or chars) -> string formed by chars of this count
36        */
37        vector<string> buckets(s.size()+1);
38        
39        for(auto it = counter.begin(); it != counter.end(); it++){
40            buckets[it->second] += string(it->second, it->first);
41        }
42        
43        string ans;
44        
45        //iterate from larger count
46        for(int i = buckets.size()-1; i >= 0; i--){
47            if(buckets[i] != ""){
48                ans += buckets[i];
49            }
50        }
51        
52        return ans;
53    }
54};
55
56//bucket sort, space optimized
57//Runtime: 44 ms, faster than 33.25% of C++ online submissions for Sort Characters By Frequency.
58//Memory Usage: 9.1 MB, less than 100.00% of C++ online submissions for Sort Characters By Frequency.
59class Solution {
60public:
61    string frequencySort(string s) {
62        unordered_map<char, int> counter;
63        
64        for(char c : s){
65            counter[c]++;
66        }
67        
68        /*
69        reserve the space
70        the count of a char(or chars) -> string formed by chars of this count
71        */
72        map<int, string> buckets;
73        
74        for(auto it = counter.begin(); it != counter.end(); it++){
75            buckets[it->second] += string(it->second, it->first);
76        }
77        
78        string ans;
79        
80        //iterate from larger count
81        for(auto it = buckets.rbegin(); it != buckets.rend(); it++){
82            ans += it->second;
83        }
84        
85        return ans;
86    }
87};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.