Skip to content

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
29
class Solution {
 public:
  vector<string> reorderLogFiles(vector<string>& logs) {
    vector<string> ans;
    vector<string> digitLogs;
    vector<pair<string, string>> 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));
    }

    ranges::sort(letterLogs, [](const pair<string, string>& a,
                                const pair<string, string>& 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<String> ans = new ArrayList<>();
    List<String> digitLogs = new ArrayList<>();
    List<String[]> 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<String[]>() {
      @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
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 x: (x[1], x[0]))
    return [identifier + ' ' + letters for identifier, letters in letterLogs] + digitLogs