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.
1function reorderLogFiles(logs) {
2 const letterLogs = [];
3 const digitLogs = [];
4 logs.forEach(log => {
5 const splitLog = log.split(' ');
6 if (isNaN(splitLog[1][0])) {
7 letterLogs.push(log);
8 } else {
9 digitLogs.push(log);
10 }
11 });
12
13 letterLogs.sort((a, b) => {
14 const [idA, ...contentA] = a.split(' ');
15 const [idB, ...contentB] = b.split(' ');
16 const cmp = contentA.join(' ').localeCompare(contentB.join(' '));
17 if (cmp !== 0) return cmp;
18 return idA.localeCompare(idB);
19 });
20 return [...letterLogs, ...digitLogs];
21}
This approach separates logs into letter and digit logs in JavaScript. Letter-logs are sorted using the sort function with a custom comparator that uses localeCompare for string comparison. Finally, the letter and digit logs are concatenated.
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.