Problem overview
Version 4 adds the -k flag. Each line is comma-separated and has at least field fields, and an empty field is allowed, as in "a,,c". sort_lines(lines, field) sorts the lines by the text of the 1-indexed field number field, compared by character code, and returns the original lines joined with \n. Lines whose fields are equal keep their original relative order. An empty list gives the empty string.
With field = 2 and ["alice,30", "bob,25", "carol,40"], the keys are "30", "25" and "40", so the result is "bob,25\nalice,30\ncarol,40". The whole line is returned, not only the key.
Approach
The earlier versions compared whole lines. Here the comparison is on a key taken out of each line, so the solution splits into two parts: a helper, extract_field, that returns the key of one line, and the sort that uses it. The sort is sort_by with a closure that compares the keys of two lines. sort_by is stable, so equal keys keep their input order, as the task requires.
The keys are compared as strings, not as numbers. For ["x,10", "y,9"] with field 2 the result is "x,10\ny,9", because "10" is less than "9" as text.
The helper builds a fresh String for each key, and the closure calls it twice per comparison, so every line's key is rebuilt many times during the sort. For a small tool that is fine and keeps the code easy to read. If the lines were very long or numerous, you could compute each key once with sort_by_cached_key, which stores the keys next to the elements while sorting. The lesson keeps the plain sort_by, which is what the steps follow.
Step by step
- Split the line at commas with
split(','). It doesn't build a vector; it gives an iterator that produces the pieces one at a time. - Take the piece at position
field - 1withnth. Fields count from 1 and positions from 0, andnthwants ausize, so the number is converted withas usize. The result is anOption, empty if the piece doesn't exist. - Fall back to an empty string with
unwrap_or(""), so a missing field counts as an empty key. - Make the key owned with
to_string(). The piece borrows from the line, and the function returns aString. This expression has no semicolon, so it is the function's result. - In
sort_lines, make a mutablesorted_linesthat is a clone oflines. - Call
sort_bywith a closure overaandb. - Compare the keys of
aandbwithcmp, passing a reference to the second key. - Join the lines with
"\n"and return.
The solution in Rust
impl Solution {
fn extract_field(line: &str, field: i32) -> String {
line.split(',')
.nth((field - 1) as usize)
.unwrap_or("")
.to_string()
}
fn sort_lines(lines: Vec<String>, field: i32) -> String {
let mut sorted_lines = lines.clone();
sorted_lines.sort_by(|a, b| {
Solution::extract_field(a, field).cmp(&Solution::extract_field(b, field))
});
return sorted_lines.join("\n");
}
}
Rust details:
&stragainstString. The helper takes&str, a borrowed view of text. In the closure,ais a&String, which Rust converts to&strautomatically at the call.- Empty fields are real pieces.
"a,,c".split(',').nth(1)isSome(""), sounwrap_orisn't even needed for it. The fallback only matters when the position is past the end:"a,b".split(',').nth(5)isNone. - The cast.
(field - 1) as usizeis fine forfieldof 1 or more. A field of 0 would give -1, whichasturns into a huge number rather than an error, and then the key is empty. The task starts counting at 1. - The reference clones the vector with
lines.clone(), althoughlinesis already owned and could be made mutable directly, as in earlier versions. Cloning is harmless here, just an extra copy. - The explicit
Solution::.extract_fieldtakes noself, so it is called through the type name.
Complexity
Time: O(n log n) comparisons for n lines. Each comparison extracts two keys, which scans each line up to the requested field, so it costs time proportional to the line lengths. Space: O(L), where L is the total text length, for the cloned lines and the joined result. The temporary keys are short-lived and each is at most one line long.
Edge cases and common mistakes
- Stability.
["b,x", "a,x", "c,w"]with field 2 gives"c,w\nb,x\na,x". The two lines with keyxkeep their input order, even thougha,xwould come first if the whole line were compared. - Empty keys.
["a,,c", "b,z,a", "c,,b"]with field 2 gives"a,,c\nc,,b\nb,z,a": the empty key sorts first and the two such lines keep their order. - Numbers sort as text.
["x,10", "y,9"]keepsx,10first. - Off-by-one. Using
fieldin place offield - 1picks the wrong piece. - Missing field. A line shorter than
field, such as"c"with field 2, has the empty key and sorts first. The task promises this won't occur, but the code handles it. For["a,b", "c"]the result is"c\na,b". - Empty list. The result is
"".
Testing
["alice,30", "bob,25", "carol,40"]with field 2 gives"bob,25\nalice,30\ncarol,40".["b,x", "a,x", "c,w"]with field 2 gives"c,w\nb,x\na,x".["a,,c", "b,z,a", "c,,b"]with field 2 gives"a,,c\nc,,b\nb,z,a".["b", "a"]with field 1 gives"a\nb".
