# 937. Reorder Data in Log Files

• Time: $O(\Sigma |\texttt{digitLogs[i]}| + \Sigma |\texttt{letterLogs[i]} |\log \Sigma |\texttt{letterLogs[i]}|)$
• Space: $O(\Sigma |\texttt{logs[i]}|)$
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 class Solution { public: vector reorderLogFiles(vector& logs) { vector ans; vector digitLogs; vector> letterLogs; for (const string& log : logs) { const int i = log.find_first_of(' '); if (isdigit(log[i + 1])) digitLogs.push_back(log); else letterLogs.emplace_back(log.substr(0, i), log.substr(i + 1)); } sort(begin(letterLogs), end(letterLogs), [](const auto& a, const auto& b) { return a.second == b.second ? a.first < b.first : a.second < b.second; }); for (const auto& [identifier, letters] : letterLogs) ans.push_back(identifier + ' ' + letters); for (const string& digitLog : digitLogs) ans.push_back(digitLog); return ans; } };
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 class Solution { public String[] reorderLogFiles(String[] logs) { List ans = new ArrayList<>(); List digitLogs = new ArrayList<>(); List letterLogs = new ArrayList<>(); for (final String log : logs) { final int i = log.indexOf(' '); if (Character.isDigit(log.charAt(i + 1))) digitLogs.add(log); else letterLogs.add(new String[] {log.substring(0, i), log.substring(i + 1)}); } Collections.sort(letterLogs, new Comparator() { @Override public int compare(String[] l1, String[] l2) { return l1[1].compareTo(l2[1]) == 0 ? l1[0].compareTo(l2[0]) : l1[1].compareTo(l2[1]); } }); for (String[] letterLog : letterLogs) ans.add(letterLog[0] + " " + letterLog[1]); for (final String digitLog : digitLogs) ans.add(digitLog); return ans.toArray(new String[0]); } }
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Solution: def reorderLogFiles(self, logs: List[str]) -> List[str]: digitLogs = [] letterLogs = [] for log in logs: i = log.index(' ') if log[i + 1].isdigit(): digitLogs.append(log) else: letterLogs.append((log[:i], log[i + 1:])) letterLogs.sort(key=lambda l: (l[1], l[0])) return [identifier + ' ' + letters for identifier, letters in letterLogs] + digitLogs