Problem overview
Version 3 adds -n. Every line is the text of a 32-bit integer, such as "-5" or "007", and sort_lines must order the lines by numeric value, ascending, returning the original strings joined with \n. Lines with equal values keep their original relative order. An empty list gives the empty string.
As text, "100" sorts before "20" because '1' is smaller than '2'. Numerically 20 comes first. For ["100", "20", "3", "10"] the result is "3\n10\n20\n100", while a text sort of the same lines gives "10\n100\n20\n3".
Approach
The lines must be compared by number but returned as the original strings, so "007" stays "007". sort_by_key fits: it takes a closure that computes a key from each element, sorts by the keys, and leaves the elements themselves unchanged. The key is the line parsed as an i32. Because sort_by_key is stable, two lines with the same number keep their input order.
It helps to see why text order fails. The text "100" against "20" is compared character by character: '1' is less than '2', so the text order says "100" is smaller, while comparing the numbers 100 and 20 says the opposite. The fix is to turn each line into a number only for the comparison, and never to replace the line itself. That separation of "what we sort by" from "what we keep" is exactly what a key function expresses.
Step by step
- Bind the input as mutable to
sorted_lines. - Sort with
sort_by_key. The closure takes a linesand returnss.parse::<i32>().unwrap().parsereturns aResult, because the text might not be a number, andunwraptakes the number out of it. - Join the lines with
"\n"and return.
The solution in Rust
impl Solution {
fn sort_lines(lines: Vec<String>) -> String {
let mut sorted_lines = lines;
sorted_lines.sort_by_key(|s| s.parse::<i32>().unwrap());
return sorted_lines.join("\n");
}
}
Rust details:
- The turbofish.
parse::<i32>()names the target type.parseis generic, and nothing else in the closure says which number type is wanted. - Leading zeros and signs.
"007".parse::<i32>()isOk(7)and"-5"isOk(-5). Parsing intoi32also covers the whole 32-bit range, so"2147483647"and"-2147483648"both work. unwrappanics on bad input. A line like"x"makesparsereturn anErr, andunwrapthen stops the program. The task promises valid integers, so that can't happen here.- The key is computed each time it is needed.
sort_by_keymay call the closure several times per element during the sort. For a task this size that is fine;sort_by_cached_keycomputes each key once if parsing becomes costly.
Complexity
Time: O(n log n) key comparisons for n lines, each needing a parse of a line of at most 11 characters. Space: O(n) for the sort's buffer and the joined string.
Edge cases and common mistakes
- Using plain
sort()gives text order:["100", "20", "3", "10"]becomes"10\n100\n20\n3". - Negative numbers.
["-5", "007", "7", "-12", "7"]gives"-12\n-5\n007\n7\n7". The numeric order puts -12 first. - Equal values.
"7"and"007"are both 7, so they keep their input order. For["7", "007", "7", "-0", "0"]the result is"-0\n0\n7\n007\n7": the first7stays ahead of007, and-0and0are equal, with-0first because it came first. - Extremes.
["2147483647", "-2147483648"]gives"-2147483648\n2147483647". - Empty list. The result is
"". - Returning the parsed numbers. The output must be the original text, so
"007"must not turn into"7".
Testing
["100", "20", "3", "10"]gives"3\n10\n20\n100".["-5", "007", "7", "-12", "7"]gives"-12\n-5\n007\n7\n7".[]gives"".
