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.
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.