Start learning free

LESSON 7 OF 69 · PROJECTS: COMMAND-LINE TOOLS

head v3 in Rust: n Larger Than the Input

Practice Read the full explanation

Same signature as v2, but now n may be larger than the number of lines. If n > lines.len() simply return all the lines (don't crash, don't pad). For this version assume n ≥ 0. If n is 0, or there are no lines, the result is the empty string.

Function signature:

fn head(lines: Vec<String>, n: i32) -> String

Example:

Input: lines = ["alpha", "beta", "gamma"], n = 10

Output: "alpha\nbeta\ngamma"

When printed:
alpha
beta
gamma

Slicing lines[0..n] past the end panics in Rust, so clamp n with (n as usize).min(lines.len()) before slicing. Rust's [T]::join then stitches the prefix together with newlines.

let end = (n as usize).min(lines.len());
return lines[0..end].join("\n");


The full solution:
impl Solution {
    fn head(lines: Vec<String>, n: i32) -> String {
        let end = (n as usize).min(lines.len());
        return lines[0..end].join("\n");
    }
}

STEP 1 OF 2
    Ctrl + Enter to check

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Head V3 in Rust, explained

    Problem overview

    This version of head keeps the signature head(lines: Vec<String>, n: i32) -> String but removes the earlier promise that n fits inside the vector. Now n may be larger than the number of lines. In that case the function returns all the lines: it must not crash and must not pad. It still assumes n >= 0. If n is 0, or there are no lines, the result is the empty string.

    For ["alpha", "beta", "gamma"] and n = 10 the result is "alpha\nbeta\ngamma".

    Approach: clamp the count, then slice

    The previous version's loop would index past the end when n is too big. The fix is to compute how many lines can actually be taken: the smaller of n and the number of lines. Taking that many lines can never go past the end of the vector. A slice of that length, joined with newlines, is the answer. The clamp is a single min, so no loop and no separator logic are needed: join places newlines only between lines.

    Step by step

    1. Clamp. let end = (n as usize).min(lines.len());. The two numbers have different types: n is an i32 and len() returns a usize. n as usize converts n first, then min picks the smaller. With 5 lines, n = 8 gives 5 and n = 3 gives 3.
    2. Slice and join. return lines[0..end].join("\n"); takes lines from index 0 up to, not including, end, and joins them. Here the lesson writes return explicitly, so the statement ends in a semicolon.

    The solution in Rust

    impl Solution {
        fn head(lines: Vec<String>, n: i32) -> String {
            let end = (n as usize).min(lines.len());
            return lines[0..end].join("\n");
        }
    }
    

    Rust details:

    • as converts between numeric types and never fails. For n >= 0, as assumed here, the result is exact. The parentheses are needed so that .min applies to the converted value.
    • Slicing past the end of a vector panics, unlike clamping the end first. With end never above the length, the slice is always valid, including when the vector is empty and end is 0.
    • return expr; and a final expression without a semicolon do the same job; both styles appear in the lessons.

    Compared with the previous version, the loop and the separator test are gone. The loop was only safe while n was guaranteed to be in range; the clamp makes the same slice safe for every non-negative n.

    Complexity

    Only the selected lines are copied, so the work is proportional to the size of the part returned: at most the whole input. The result string is the extra space.

    Edge cases and common mistakes

    • n beyond the length. Clamping returns every line: ["alpha", "beta", "gamma"] with n = 10 gives "alpha\nbeta\ngamma".
    • n = 0. end is 0, so the result is "".
    • No lines. With an empty vector and n = 4, end is 0 and the result is "".
    • A negative n. It is outside this version's assumption. A cast makes it wrap: -2i32 as usize is 18446744073709551614, which min then clamps to the length, so the function would return every line. That is not a meaningful answer, only the result of the wrap-around.
    • Casting the wrong way. Converting lines.len() to i32 is possible, but the slice bounds need usize anyway, so converting n keeps the code shortest.
    • Mixing the two integer types. Writing n.min(lines.len()) without the cast is a compile error, because min needs both sides to have the same type.

    Testing

    alpha, beta, gamma, n = 10         ->  "alpha\nbeta\ngamma"
    alpha..epsilon (5 lines), n = 2    ->  "alpha\nbeta"
    [], n = 4                          ->  ""
    alpha..epsilon (5 lines), n = 0    ->  ""
    
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free