559. Reorder Data in Log Files
You are handed an array of log lines, logs. Every line starts with an alphanumeric identifier (its first token) followed by at least one more token. After the identifier a line is one of two kinds:
- a letter-log — every remaining token is made of lowercase letters,
- a digit-log — every remaining token is made of digits.
Your function receives logs and returns the same lines rearranged so that:
- every letter-log appears before any digit-log,
- letter-logs are ordered lexicographically by their content (everything after the identifier); when two contents are identical, the tie is broken by comparing identifiers,
- digit-logs keep exactly the relative order they arrived in.
The ordering rules pin down a single valid answer.
Example 1:
Input: logs = ["a1 9 2 3 1", "g1 act car", "zo4 4 7", "ab1 off key dog", "a8 act zoo"]
Output: ["g1 act car", "a8 act zoo", "ab1 off key dog", "a1 9 2 3 1", "zo4 4 7"]
Explanation: The three letter-logs sort by content: "act car" < "act zoo" < "off key dog". The two digit-logs follow, still in arrival order.
Example 2:
Input: logs = ["t2 13 121", "r1 box", "x1 box", "t3 8 5"]
Output: ["r1 box", "x1 box", "t2 13 121", "t3 8 5"]
Explanation: Both letter-logs have the same content "box", so the identifiers decide: "r1" < "x1". Digit-logs trail in original order.
Constraints:
- 1 ≤ logs.length ≤ 100
- 3 ≤ logs[i].length ≤ 100
- Every log has an alphanumeric identifier and at least one word after it.
- After its identifier, a log's words are either all lowercase letters or all digits; tokens are separated by single spaces.
Hints:
A log's kind is decided by one character: the first character after the first space. If it's a digit, the whole log is a digit-log.
You never sort the digit-logs at all — pull them aside, sort only the letter-logs by (content, identifier), then append the digit-logs untouched.
One pass, one sort: a stable sort with the key (is-digit-flag, content, identifier) does everything — every digit-log maps to the same key, and stability keeps their arrival order.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: logs = ["a1 9 2 3 1", "g1 act car", "zo4 4 7", "ab1 off key dog", "a8 act zoo"]
Expected output: ["g1 act car", "a8 act zoo", "ab1 off key dog", "a1 9 2 3 1", "zo4 4 7"]