Sponsored
This approach involves separating the logs into letter-logs and digit-logs. We then use a custom sorting function to sort the letter-logs based on their content first and their identifiers second, before finally appending the digit-logs to the sorted letter-logs.
Time complexity is O(M*N*logN), where N is the number of logs and M is the maximum length of a single log. Sorting the letter logs is the most time-consuming operation.
Space complexity is O(N), for storing the letter-logs and digit-logs separately.
1def reorderLogFiles(logs):
2 letter_logs = []
3 digit_logs = []
4 for log in logs:
5 if log.split()[1].isdigit():
6 digit_logs.append(log)
7 else:
8 letter_logs.append(log)
9 letter_logs.sort(key=lambda log: (log.split()[1:], log.split()[0]))
10 return letter_logs + digit_logs
This solution defines a function which separates the logs into letter-logs and digit-logs. It uses Python's built-in sort functionality with a custom sorting key. The key first compares everything after the identifier, and then by identifier itself.
This approach intends to utilize a two-pass operation, where in the first pass it processes and categorizes letter-logs and digit-logs, and in the second pass it performs an in-place sort on the letter logs. Lastly, it reconstructs the original array by appending digit-logs after the sorted letter-logs.
Time complexity is O(M*N*logN) due to the sorting of letter-logs using qsort.
Space complexity is O(1), because sorting and operations are done in place.
1using System;
2using System.Linq;
3
public class Solution {
public string[] ReorderLogFiles(string[] logs) {
var digitLogs = logs.Where(log => char.IsDigit(log.Split(' ')[1][0])).ToList();
var letterLogs = logs.Except(digitLogs).ToList();
letterLogs.Sort((log1, log2) => {
var split1 = log1.Split(new char[] {' '}, 2);
var split2 = log2.Split(new char[] {' '}, 2);
int cmp = string.Compare(split1[1], split2[1]);
if (cmp != 0) return cmp;
return string.Compare(split1[0], split2[0]);
});
letterLogs.AddRange(digitLogs);
return letterLogs.ToArray();
}
}
The C# solution identifies digit logs using LINQ, and utilizes a cohesive sort method with a custom comparison for letter-logs. The sorted collections are finally concatenated into a final result array.