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")
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
