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
- Clamp.
let end = (n as usize).min(lines.len());. The two numbers have different types:nis ani32andlen()returns ausize.n as usizeconvertsnfirst, thenminpicks the smaller. With 5 lines,n = 8gives 5 andn = 3gives 3. - 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 writesreturnexplicitly, 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:
asconverts between numeric types and never fails. Forn >= 0, as assumed here, the result is exact. The parentheses are needed so that.minapplies to the converted value.- Slicing past the end of a vector panics, unlike clamping the end first. With
endnever above the length, the slice is always valid, including when the vector is empty andendis 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
nbeyond the length. Clamping returns every line:["alpha", "beta", "gamma"]withn = 10gives"alpha\nbeta\ngamma".n = 0.endis 0, so the result is"".- No lines. With an empty vector and
n = 4,endis 0 and the result is"". - A negative
n. It is outside this version's assumption. A cast makes it wrap:-2i32 as usizeis 18446744073709551614, whichminthen 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()toi32is possible, but the slice bounds needusizeanyway, so convertingnkeeps the code shortest. - Mixing the two integer types. Writing
n.min(lines.len())without the cast is a compile error, becauseminneeds 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 -> ""
