Same signature as v2, but now n may be larger than the number of lines. If n > lines.count simply return all the lines (don't crash, don't pad). For this version assume n ≥ 0. If n is 0, or there are no lines, the result is the empty string.
Function signature:
func head(_ lines: [String], _ n: Int) -> String
Example:
Input: lines = ["alpha", "beta", "gamma"], n = 10 Output: "alpha\nbeta\ngamma" When printed: alpha beta gamma
Slicing a Swift array with
lines[0..<n] when n > lines.count traps. So clamp n with min(n, lines.count) first.
let end = min(n, lines.count)
return lines[0..<end].joined(separator: "\n")
The full solution:
class Solution {
func head(_ lines: [String], _ n: Int) -> String {
let end = min(n, lines.count)
return lines[0..<end].joined(separator: "\n")
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
