Start learning free

LESSON 23 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Sort V3 in Rust: Numeric Sort with sort_by_key

Practice Read the full explanation

Build the next version of the Unix sort command, this time with the -n flag baked in. Each input line is the string form of an integer that fits in 32 bits (an optional leading -, no leading +; leading zeros such as "007" are allowed). Sort the lines numerically (not lexicographically) in ascending order, and return the original strings joined by newlines (\n). Lines with the same numeric value keep their original relative order (a stable sort). The real sort -n would break such ties by comparing the text; this version does not. If the list is empty, return the empty string.

Note: lexicographic sort would put "100" before "20"; numeric sort puts 20 before 100.

Function signature:

fn sort_lines(lines: Vec<String>) -> String

Example:

Input: lines = ["100", "20", "3", "10"]

Output: "3\n10\n20\n100"

When printed:
3
10
20
100

Sort by a key that parses each string into an i32 with parse, then build the result with the slice join method.

The full solution:
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");
    }
}

STEP 1 OF 3
    Ctrl + Enter to check

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Sort V3 in Rust, explained

    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

    1. Bind the input as mutable to sorted_lines.
    2. Sort with sort_by_key. The closure takes a line s and returns s.parse::<i32>().unwrap(). parse returns a Result, because the text might not be a number, and unwrap takes the number out of it.
    3. 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. parse is generic, and nothing else in the closure says which number type is wanted.
    • Leading zeros and signs. "007".parse::<i32>() is Ok(7) and "-5" is Ok(-5). Parsing into i32 also covers the whole 32-bit range, so "2147483647" and "-2147483648" both work.
    • unwrap panics on bad input. A line like "x" makes parse return an Err, and unwrap then 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_key may call the closure several times per element during the sort. For a task this size that is fine; sort_by_cached_key computes 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 first 7 stays ahead of 007, and -0 and 0 are equal, with -0 first 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 "".
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free