Reorder Data in Log Files
Medium · Arrays & Hashing · Array · String · Sorting
Problem
You are given an array of strings logs. Each log is a space-separated string whose first word is an identifier made of lowercase letters and digits. The rest of a log is either all lowercase words (a letter-log) or all words of digits (a digit-log).
Reorder the logs and return them by these rules:
- Every letter-log comes before every digit-log.
- Letter-logs are sorted by their content (everything after the identifier); logs with equal content are sorted by identifier.
- Digit-logs keep their original relative order.
Examples
Input: logs = ["x1 9 2","b7 act car","a2 act car","z0 zoo","m5 4 4"] Output: ["a2 act car","b7 act car","z0 zoo","x1 9 2","m5 4 4"]
Two letter-logs share the content "act car", so their identifiers decide; the digit-logs follow in input order.
Input: logs = ["d1 3","c4 hello"] Output: ["c4 hello","d1 3"]
The letter-log moves ahead of the digit-log.
Input: logs = ["a1 zoo","b1 act zoo","c1 act"] Output: ["c1 act","b1 act zoo","a1 zoo"]
"act" < "act zoo" < "zoo": content decides before identifiers are looked at.
Constraints
- 1 <= len(logs) <= 100
- 3 <= len(logs[i]) <= 100
- Words in a log are separated by single spaces
- Every log has an identifier followed by at least one word
Approaches
- Baseline: insertion sort with one comparison function — time O(n² · L), space O(n · L)
Follow-up
What if digit-logs led, ordered by their numbers? Or file names had to be sorted with numbers compared by value? Both use cases are a partition or a key away from this one.
Related problems
Start free on Cariara · Coding problems · System design studio