Build the next version of the Unix sort command, this time with the -k flag baked in. Each input line is comma-separated and is guaranteed to have at least field fields (a field may be empty, as in "a,,c"). Given a 1-indexed field number, sort the lines stably by the value at that field, compared as strings by character code, and return the original lines joined by newlines (\n). Lines whose fields are equal keep their original relative order. This matches the real command sort -t, -k N,N -s in the C locale. If the list is empty, return the empty string.
Function signature:
fn sort_lines(lines: Vec<String>, field: i32) -> String
Example:
Input: field = 2, lines = ["alice,30", "bob,25", "carol,40"] Output: "bob,25\nalice,30\ncarol,40" When printed: bob,25 alice,30 carol,40
Rust's slice
sort_by is a stable sort (use it, not sort_unstable_by). Write a helper that extracts the field by splitting on commas, compare those keys in the comparator, and join the result with the built-in join.
fn extract_field(line: &str, field: i32) -> String {
line.split(',').nth((field - 1) as usize).unwrap_or("").to_string()
}
The full solution:
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");
}
}
Free plan: 30 tutor messages. Premium is unlimited.
