Same signature as v2, but now n may be larger than the number of lines. If n > lines.size 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:
fun head(lines: List<String>, n: Int): String
Example:
Input: lines = ["alpha", "beta", "gamma"], n = 10 Output: "alpha\nbeta\ngamma" When printed: alpha beta gamma
lines.subList(0, n) with n > lines.size throws. So clamp n with minOf(n, lines.size) first.
val end = minOf(n, lines.size)
return lines.subList(0, end).joinToString("\n")
The full solution:
class Solution {
fun head(lines: List<String>, n: Int): String {
val end = minOf(n, lines.size)
return lines.subList(0, end).joinToString("\n")
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
