Approach
Sorting and greedy selection
For Sort Vowels by Frequency, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 39 lines of C++ from the credited upstream file sort-vowels-by-frequency.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 3 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 string sortVowels(string s) {8 static const string VOWELS = "aeiou";9 10 unordered_map<char, vector<int>> cnt;11 for (int i = 0; i < size(s); ++i) {12 if (VOWELS.find(s[i]) == string::npos) {13 continue;14 }15 if (!cnt.count(s[i])) {16 cnt[s[i]] = vector<int>{0, i};17 }18 ++cnt[s[i]][0];19 }20 vector<tuple<char, int, int>> sorted_cnt;21 for (const auto& [k, v] : cnt) {22 sorted_cnt.emplace_back(k, v[0], v[1]);23 }24 ranges::sort(sorted_cnt, [](const auto& a, const auto& b) {25 return get<1>(a) == get<1>(b) ? get<2>(a) > get<2>(b) : get<1>(a) < get<1>(b);26 });27 for (int i = 0; i < size(s); ++i) {28 if (VOWELS.find(s[i]) == string::npos) {29 continue;30 }31 s[i] = get<0>(sorted_cnt.back());32 if (!(--get<1>(sorted_cnt.back()))) {33 sorted_cnt.pop_back();34 }35 }36 return s;37 }38};39