Same signature as v2/v3, but now n may be negative. Real head -n -K prints all lines except the last K. So when n < 0 return all lines except the last |n|; when n ≥ 0 behave exactly like v3 (return the first n, capped at the input length). If |n| is at least the number of lines, nothing is left, so return the empty string.
Function signature:
fun head(lines: List<String>, n: Int): String
Example (negative n):
Input: lines = ["a", "b", "c", "d", "e"], n = -2 Output: "a\nb\nc" When printed: a b c
Kotlin's
subList needs an explicit, non-negative end index. Branch on the sign of n: when n < 0, the end index is lines.size + n; otherwise it's minOf(n, lines.size). Don't forget maxOf(0, ...) for the negative branch in case |n| exceeds the list length.
val end: Int
if (n < 0) {
end = maxOf(0, lines.size + n)
} else {
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: Int
if (n < 0) {
end = maxOf(0, lines.size + n)
} else {
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
