Approach
Sorting and greedy selection
For Sort Features by Popularity, 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
- 32 lines of C++ from the credited upstream file 1772.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 5 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.
1class Solution {2 public:3 vector<string> sortFeatures(vector<string>& features,4 vector<string>& responses) {5 vector<string> ans;6 vector<pair<int, int>> featCount; 7 unordered_map<string, int> count;8 9 for (const string& res : responses) {10 istringstream iss(res);11 unordered_set<string> seen;12 for (string token; getline(iss, token, ' ');)13 seen.insert(token);14 for (const string& token : seen)15 ++count[token];16 }17 18 for (int i = 0; i < features.size(); ++i)19 featCount.emplace_back(i, count[features[i]]);20 21 ranges::sort(featCount, ranges::less{}, [](const pair<int, int>& a) {22 const auto& [i, count] = a;23 return pair<int, int>{-count, i};24 });25 26 for (const auto& [i, count] : featCount)27 ans.push_back(features[i]);28 29 return ans;30 }31};32