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.
1import java.util.*;
2public class ReorderLogs {
3 public String[] reorderLogFiles(String[] logs) {
4 Comparator<String> myComp = new Comparator<String>() {
5 public int compare(String log1, String log2) {
6 String[] split1 = log1.split(" ", 2);
7 String[] split2 = log2.split(" ", 2);
8 boolean isDigit1 = Character.isDigit(split1[1].charAt(0));
9 boolean isDigit2 = Character.isDigit(split2[1].charAt(0));
10 if (!isDigit1 && !isDigit2) {
11 int cmp = split1[1].compareTo(split2[1]);
12 if (cmp != 0) return cmp;
13 return split1[0].compareTo(split2[0]);
14 }
15 return isDigit1 ? (isDigit2 ? 0 : 1) : -1;
16 }
17 };
18 Arrays.sort(logs, myComp);
19 return logs;
20 }
21}
This implementation uses Java's Comparator interface to define a custom sorting logic. We distinctly separate the digit and letter logs, applying an alphabetical ordering to letter-logs and keeping digit-logs in relative order.
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.