Same signature as v2, but now n may be larger than the number of lines. If n > lines.length 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:
def head(lines: Array[String], n: Int): String
Example:
Input: lines = ["alpha", "beta", "gamma"], n = 10 Output: "alpha\nbeta\ngamma" When printed: alpha beta gamma
Compute a capped
end with math.min(n, lines.length) so you only take the safe prefix, then join it with newlines.
val end = math.min(n, lines.length)
return lines.slice(0, end).mkString("\n")
The full solution:
class Solution {
def head(lines: Array[String], n: Int): String = {
val end = math.min(n, lines.length)
return lines.slice(0, end).mkString("\n")
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
