937. Reorder Data in Log Files
Explanation
To solve this problem, we need to separate the letter-logs from the digit-logs, sort the letter-logs according to the given rules, and then append the digit-logs at the end in their original order.
- Separate the logs into two lists: letter-logs and digit-logs.
- Sort the letter-logs based on content and identifier.
- Concatenate the sorted letter-logs with the digit-logs.
Time Complexity: The time complexity of this solution is O(N*logN) where N is the number of logs.
Space Complexity: The space complexity is O(N).
import java.util.Arrays;
import java.util.Comparator;
class Solution {
public String[] reorderLogFiles(String[] logs) {
Arrays.sort(logs, new Comparator<String>() {
@Override
public int compare(String log1, String log2) {
String[] split1 = log1.split(" ", 2);
String[] split2 = log2.split(" ", 2);
boolean isDigit1 = Character.isDigit(split1[1].charAt(0));
boolean isDigit2 = Character.isDigit(split2[1].charAt(0));
if (!isDigit1 && !isDigit2) {
int cmp = split1[1].compareTo(split2[1]);
if (cmp != 0) {
return cmp;
}
return split1[0].compareTo(split2[0]);
} else if (isDigit1 && isDigit2) {
return 0;
} else if (isDigit1) {
return 1;
} else {
return -1;
}
}
});
return logs;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.