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.
1#include <stdio.h>
2
The solution in C utilizes two pointers to distinguish between digit and letter logs and uses qsort for in-place sorting of letter logs. The custom compare function accurately handles comparison based on the directive content and identifier.