Start learning free

LESSON 21 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Sort V1 in Rust: Ascending Alphabetical Order

Practice Read the full explanation

Build a tiny version of the Unix sort command. Given a list of lines, return them sorted in ascending order by character code (like LC_ALL=C sort: uppercase letters come before lowercase ones, "Zebra" before "apple", and an empty line comes first), joined by newline characters (\n). Duplicates are all kept. If the list is empty, return the empty string.

Function signature:

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

Example:

Input: lines = ["banana", "apple", "cherry"]

Output: "apple\nbanana\ncherry"

When printed:
apple
banana
cherry

You already own the input vector, so bind it as mutable, sort it with sort(), then combine the lines with the slice join("\n") method.

The full solution:
impl Solution {
    fn sort_lines(lines: Vec<String>) -> String {
        let mut sorted_lines = lines;
        sorted_lines.sort();
        return sorted_lines.join("\n");
    }
}

STEP 1 OF 3
    Ctrl + Enter to check

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Sort V1 in Rust, explained

    Problem overview

    The first version of the sort tool is small. sort_lines takes a Vec<String>, puts the lines in ascending order and returns them as one String with \n between lines. Duplicates stay, and an empty list gives the empty string.

    "Ascending" means by character code, like LC_ALL=C sort. Every uppercase letter has a smaller code than every lowercase letter, so "Zebra" comes before "apple", and the empty line comes first of all. For ["banana", "apple", "cherry"] the result is "apple\nbanana\ncherry".

    Approach

    Rust's String already knows how to compare itself with another String: it compares the underlying bytes from the start, and the first difference decides. For ASCII text that is the character-code order the task asks for, and a string that is a prefix of another sorts first. So the work is two calls: sort the vector, then join it.

    The comparison goes one position at a time. "ab" against "b" is decided at the first character, where 'a' is smaller, so "ab" comes first. "a" against "ab" has no difference in the shared part, and the shorter string sorts first. A capital letter against a lowercase one is decided by the code too: "Z" is less than "a", which is why ["Cherry", "apple"] keeps Cherry in front. The comparison is on bytes, so it matches character-code order for plain ASCII. A letter such as é is stored as bytes with large values and sorts after z.

    Step by step

    1. Take ownership as a mutable binding. The vector arrives by value, so the function owns it. Sorting reorders the elements in place, and that needs a mut binding, so the first line moves lines into let mut sorted_lines.
    2. Sort in place with sort(). It returns nothing; the vector itself is changed.
    3. Join the lines with join("\n"). The separator goes only between two lines, so the output has no trailing newline.

    The solution in Rust

    impl Solution {
        fn sort_lines(lines: Vec<String>) -> String {
            let mut sorted_lines = lines;
            sorted_lines.sort();
            return sorted_lines.join("\n");
        }
    }
    

    Details that matter in Rust:

    • sort() works in place and returns (). Writing let sorted = lines.sort(); would give you the unit value, not a sorted vector.
    • Why mut. Without it the compiler rejects the call with "cannot borrow as mutable". Rust requires the binding to be declared mutable before a method can change the value through it.
    • Stability. sort() is a stable sort, which makes no visible difference here, since equal strings are indistinguishable.
    • join on a vector of strings. It is a method of slices of strings, and the vector coerces to a slice automatically. It returns a new String.

    Complexity

    Time: O(n log n) comparisons for n lines, each comparison costing up to the length of the shorter line. Space: O(n) at most, since the sort may use a temporary buffer and the joined string holds a copy of all the text.

    Edge cases and common mistakes

    • Case. ["apple", "Zebra", "", "apple"] gives "\nZebra\napple\napple": the empty line first, then uppercase, then lowercase, with both copies of apple kept.
    • Empty list. Joining zero lines gives "", with no special case needed.
    • Not alphabetical in the dictionary sense. Case-insensitive ordering would need a different comparison. This tool deliberately uses plain code order.
    • Forgetting mut is the most common compile error here.

    Testing

    • ["banana", "apple", "cherry"] gives "apple\nbanana\ncherry".
    • ["apple", "Zebra", "", "apple"] gives "\nZebra\napple\napple".
    • [] 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