Engineering platform~20 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-937sorting
A platform team prints service log lines on a console. Each line is an identifier, one space, and a body of words and numbers, such as k1 retry at noon. Text lines have a body that starts with a letter. Numeric lines have a body that starts with a digit.
Write order_log_lines(logs).
logs is <id> <body>. The id has no spaces, and all ids are different.Input: logs = ["m3 error disk full", "d7 5 12", "k1 retry at noon", "b4 error disk full", "x2 3 3 3"]
Output: ["b4 error disk full", "m3 error disk full", "k1 retry at noon", "d7 5 12", "x2 3 3 3"]Split each line into its id and body. Text lines are sorted by body and then id, and numeric lines stay where they were, in order.
| Line | Kind | Sort key (body, id) |
|---|---|---|
| m3 error disk full | text | error disk full, m3 |
| d7 5 12 | numeric | not sorted: keeps its place |
| k1 retry at noon | text | retry at noon, k1 |
| b4 error disk full | text | error disk full, b4 |
| x2 3 3 3 | numeric | not sorted: keeps its place |
The two error disk full bodies tie, so the ids b4 and m3 decide. The result is ["b4 error disk full", "m3 error disk full", "k1 retry at noon", "d7 5 12", "x2 3 3 3"].
Input: logs = ["a1 5", "b1 3"]
Output: ["a1 5", "b1 3"]Both lines are numeric, so they keep their order: ["a1 5", "b1 3"].
Input: logs = ["a1 zzz", "b1 aaa"]
Output: ["b1 aaa", "a1 zzz"]The body decides before the id, so b1 comes first: ["b1 aaa", "a1 zzz"].
0 ≤ logs.length ≤ 100,000 (log lines)a to z, 0 to 9 and the space.Comparing every line with every other line costs about n × n comparisons, which is 10^10 at n = 100,000. A sort costs n log n comparisons, and one pass to split the lines costs n.