Start learning free

LESSON 8 OF 69 · PROJECTS: COMMAND-LINE TOOLS

head v4 in Rust: Negative n Drops the Last Lines

Practice Read the full explanation

Same signature as v2/v3, but now n may be negative. Real head -n -K prints all lines except the last K. So when n < 0 return all lines except the last |n|; when n ≥ 0 behave exactly like v3 (return the first n, capped at the input length). If |n| is at least the number of lines, nothing is left, so return the empty string.

Function signature:

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

Example (negative n):

Input: lines = ["a", "b", "c", "d", "e"], n = -2

Output: "a\nb\nc"

When printed:
a
b
c

Branch on the sign of n: when n < 0, the end index is lines.len() as i32 + n (with a max(0, ...) floor); otherwise it's min(lines.len() as i32, n). Then slice and call join("\n") — Rust string slices have a built-in join.

let end: usize;
if n < 0 {
    end = std::cmp::max(0, lines.len() as i32 + n) as usize;
} else {
    end = std::cmp::min(lines.len() as i32, n) as usize;
}
lines[0..end].join("\n")


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

STEP 1 OF 5
    Ctrl + Enter to check

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Head V4 in Rust, explained

    Problem overview

    In this version of head(lines: Vec<String>, n: i32) -> String, n may be negative. Like the real head -n -K, a negative n means "all lines except the last |n|". For n >= 0 the function behaves as before: the first n lines, capped at the input length. If |n| is at least the number of lines, nothing is left and the result is the empty string.

    For ["a", "b", "c", "d", "e"] and n = -2, the result is "a\nb\nc".

    Approach: one end index for both signs

    Both cases are the same operation: take the lines from the start up to some end index. Only the way to find that index changes:

    • For n >= 0, the end index is n, capped at the number of lines.
    • For n < 0, the end index is the number of lines plus n, which walks back from the end by |n|. If that goes below 0, it stops at 0.

    With five lines and n = -2 the end index is 5 - 2 = 3, so three lines are kept. Once end is known, one slice and one join finish the job for either sign.

    Step by step

    1. Declare end without a value. let end: usize; is allowed in Rust as long as every path assigns it exactly once before it is read. The type is written out because there is nothing yet to infer it from.
    2. Split by sign. An if n < 0 { ... } else { ... }.
    3. Negative case. end = std::cmp::max(0, lines.len() as i32 + n) as usize;. The length is converted to i32 so that adding a negative n can go below zero, which a usize cannot. max(0, ...) floors the count at 0. The final as usize converts the non-negative result back.
    4. Non-negative case. end = std::cmp::min(lines.len() as i32, n) as usize;. This is the cap from the previous version, with the same two conversions.
    5. Slice and join. lines[0..end].join("\n") works for either branch.

    The solution in Rust

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

    Rust details:

    • The signed conversion is the reason for the casts. Computing lines.len() + n directly doesn't compile (a usize plus an i32), and doing the subtraction in usize could not go below zero: such arithmetic wraps in an optimized build and panics in a debug build. Working in i32 and clamping with max sidesteps both.
    • std::cmp::max and std::cmp::min are functions that take two arguments, an alternative to the .min() method used earlier.
    • end is assigned once on each path, so it needs no mut. The compiler checks that every path assigns it before the last line uses it.
    • A cast from usize to i32 truncates for lengths beyond 2,147,483,647 lines, which is far beyond any realistic input here.

    Complexity

    The index arithmetic is constant time, and only the selected lines are copied into the result, so the work is proportional to the size of the output.

    Edge cases and common mistakes

    • Dropping exactly everything. For five lines and n = -5, the end index is 0 and the result is "".
    • Dropping more than exists. With n = -9 the sum is -4, and max raises it to 0, again giving "". Without the clamp, a negative index would be cast to a huge usize and the slice would panic.
    • n = -1. Drops only the last line: "a\nb\nc\nd" for the five-line input.
    • n = 0. Takes the non-negative path, so the result is "".
    • n larger than the length. n = 99 is capped at 5, so all five lines come back.
    • Empty input. With no lines and n = -1, the sum is -1, clamped to 0, so the result is "".

    Testing

    a..e, n = -2   ->  "a\nb\nc"
    a..e, n = -1   ->  "a\nb\nc\nd"
    a..e, n = -5   ->  ""
    a..e, n = -9   ->  ""
    a..e, n = 0    ->  ""
    a..e, n = 3    ->  "a\nb\nc"
    a..e, n = 99   ->  "a\nb\nc\nd\ne"
    [], n = -1     ->  ""
    
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free