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:
func head(_ lines: [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
Use a range slice to grab the first 10 lines, but cap the upper bound at
lines.count when the array is shorter than 10. Then call joined(separator: "\n") on the slice.
Compute
let end = min(10, lines.count), then slice lines[0..<end].
The full solution:
class Solution {
func head(_ lines: [String]) -> String {
let end = min(10, lines.count)
return lines[0..<end].joined(separator: "\n")
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
