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