Approach
Sorting and greedy selection
For Reorder Data in Log Files, 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
- 31 lines of C++ from the credited upstream file 937.cpp.
- The implementation visibly relies on sequence storage.
- 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.
1class Solution {2 public:3 vector<string> reorderLogFiles(vector<string>& logs) {4 vector<string> ans;5 vector<string> digitLogs;6 vector<pair<string, string>> letterLogs;7 8 for (const string& log : logs) {9 const int i = log.find_first_of(' ');10 if (isdigit(log[i + 1]))11 digitLogs.push_back(log);12 else13 letterLogs.emplace_back(log.substr(0, i), log.substr(i + 1));14 }15 16 ranges::sort(letterLogs, ranges::less{},17 [](const pair<string, string>& letterLog) {18 const auto& [identifier, letters] = letterLog;19 return pair<string, string>{letters, identifier};20 });21 22 for (const auto& [identifier, letters] : letterLogs)23 ans.push_back(identifier + ' ' + letters);24 25 for (const string& digitLog : digitLogs)26 ans.push_back(digitLog);27 28 return ans;29 }30};31