Problem overview
Version 2 of the sort tool adds the -r flag: sort_lines returns the lines in descending order by character code, joined with \n. It is the exact reverse of version 1, so lowercase letters now come before uppercase ones. Duplicates are kept and an empty list gives the empty string. For ["banana", "apple", "cherry"] the result is "cherry\nbanana\napple". The previous version sorted ascending with a plain sort().
Approach
A plain sort() always goes ascending, so the lesson needs a custom comparison. sort_by takes a closure that receives two elements, a and b, and answers with an Ordering: Less if a belongs first, Equal, or Greater. Ascending order is a.cmp(b). Swapping the two operands, b.cmp(a), flips every answer, which gives descending order. Reversing the sorted vector afterwards would work too, but a swapped comparison does it in one step.
Comparing by swapped operands is a general trick. Any ascending comparison turns into a descending one by exchanging a and b. For example, with the lines ["banana", "apple", "Cherry", ""], the ascending order is ["", "Cherry", "apple", "banana"], and the descending order is exactly that list reversed: ["banana", "apple", "Cherry", ""]. Because the two orders mirror each other, calling sort() followed by reverse() gives the same result for strings. The difference shows up with equal elements: a swapped comparison keeps equal elements in their input order, while reversing a sorted vector flips them. For identical strings you can't see that difference, since equal strings look the same wherever they land.
The three possible answers of a comparison are the variants of the Ordering enum. For text, "b".cmp("a") is Greater and "Z".cmp("a") is Less, the same character-code rule as in the first version. In the closure, b.cmp(a) returns Less when b is smaller than a, and Less tells sort_by to place a before b. This is why the larger text ends up first.
Step by step
- Bind the input as mutable to
sorted_lines, because sorting changes the vector. - Call
sort_bywith a closure overaandbthat returnsb.cmp(a). The closure decides where each pair goes. - Return the join as the last expression, without
returnand without a semicolon. That expression is the function's value.
The solution in Rust
impl Solution {
fn sort_lines(lines: Vec<String>) -> String {
let mut sorted_lines = lines;
sorted_lines.sort_by(|a, b| b.cmp(a));
sorted_lines.join("\n")
}
}
Rust details:
- The closure's parameters are references. Here
aandbare&String. The methodcmptakes a reference to the other value, andbalready is one, sob.cmp(a)needs no extra&. - Expression, not statement. A semicolon after
sorted_lines.join("\n")would turn it into a statement and the function would return(), which fails to compile against the declaredString. - Ordering.
cmpcomes from theOrdtrait, whichStringimplements with byte-by-byte comparison.
Complexity
Time: O(n log n) comparisons for n lines, each costing up to the length of the shorter line. Space: O(n) for the sort's buffer and the joined result.
Edge cases and common mistakes
- Writing
a.cmp(b). That is ascending order, the previous version's result. - Case.
["apple", "Zebra", "", "apple"]gives"apple\napple\nZebra\n". The empty line sorts last, so the output ends with a newline character. - Empty list. The result is
"". - Duplicates stay, side by side.
Testing
["banana", "apple", "cherry"]gives"cherry\nbanana\napple".["apple", "Zebra", "", "apple"]gives"apple\napple\nZebra\n".[]gives"".
