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 isn, capped at the number of lines. - For
n < 0, the end index is the number of lines plusn, 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
- Declare
endwithout 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. - Split by sign. An
if n < 0 { ... } else { ... }. - Negative case.
end = std::cmp::max(0, lines.len() as i32 + n) as usize;. The length is converted toi32so that adding a negativencan go below zero, which ausizecannot.max(0, ...)floors the count at 0. The finalas usizeconverts the non-negative result back. - 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. - 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() + ndirectly doesn't compile (ausizeplus ani32), and doing the subtraction inusizecould not go below zero: such arithmetic wraps in an optimized build and panics in a debug build. Working ini32and clamping withmaxsidesteps both. std::cmp::maxandstd::cmp::minare functions that take two arguments, an alternative to the.min()method used earlier.endis assigned once on each path, so it needs nomut. The compiler checks that every path assigns it before the last line uses it.- A cast from
usizetoi32truncates 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 = -9the sum is -4, andmaxraises it to 0, again giving"". Without the clamp, a negative index would be cast to a hugeusizeand 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"".nlarger than the length.n = 99is 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 -> ""
