LeetCode Solutions

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]}|)$

			

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));
    }

    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;
  }
};
			

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]);
  }
}
			

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