Build a tiny version of the Unix head command. Given a list of lines, return the first 10 lines joined by newline characters (\n). If the input has fewer than 10 lines, return all of them. If there are no lines at all, return the empty string.
Function signature:
fn head(lines: Vec<String>) -> String
Example:
Input: lines = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"] Output: "a\nb\nc\nd\ne\nf\ng\nh\ni\nj" When printed: a b c d e f g h i j
Compute the end index, capping it at
lines.len() so a short input never panics. Then slice the vector and call join("\n") — Rust string slices have a built-in join.
Compute
let end = lines.len().min(10), then return lines[0..end].join("\n").
The full solution:
impl Solution {
fn head(lines: Vec<String>) -> String {
let end = lines.len().min(10);
lines[0..end].join("\n")
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
