Extend your head command to take an integer n and return the first n lines of lines, joined by newline characters (\n). For this version you may assume 0 ≤ n ≤ lines.length. If n is 0 the result is the empty string.
Function signature:
def head(lines: Array[String], n: Int): String
Example:
Input: lines = ["alpha", "beta", "gamma", "delta", "epsilon"], n = 3 Output: "alpha\nbeta\ngamma" When printed: alpha beta gamma
Use
lines.slice(0, n) for the first n elements, then mkString("\n"). Since the problem guarantees n ≤ lines.length, no min needed.
Combine the slice and join into one expression:
return lines.slice(0, n).mkString("\n")
The full solution:
class Solution {
def head(lines: Array[String], n: Int): String = {
return lines.slice(0, n).mkString("\n")
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
