Problem overview
The signature stays fun head(lines: List<String>, n: Int): String, but now n may be negative. Real head -n -K prints every line except the last K, and this version does the same:
- When
n < 0, return all lines except the last|n|. - When
n >= 0, behave as before: the firstnlines, capped at the number of lines. - If
|n|is at least the number of lines, nothing is left and the result is"".
For ["a", "b", "c", "d", "e"] and n = -2 the result is "a\nb\nc": the last two lines are dropped.
Approach
Both cases are still "a prefix of the list", so one subList(0, end) call covers them. Only the end index differs:
- for
n >= 0,end = minOf(n, lines.size), as in the previous version; - for
n < 0, you keeplines.size + nlines. With 5 lines andn = -2that is 3. If|n|is bigger than the list, the sum goes below zero, so clamp it at 0 withmaxOf.
The sign of n decides which formula to use, so the code branches once and then uses the same subList and joinToString line for both.
Step by step
- Declare
val end: Intwith no value. Kotlin allows avalwithout an initializer as long as every path assigns it exactly once. The type is required here, since there is no value to infer it from. - Write the if/else:
n < 0on one side and every othernon the other. - Negative branch:
end = maxOf(0, lines.size + n).maxOfreturns the larger of its arguments, so the result never drops below 0. - Other branch:
end = minOf(n, lines.size), the cap from the previous version. - Return
lines.subList(0, end).joinToString("\n"). Both branches have setend, so this line works for either sign.
The solution in Kotlin
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")
}
}
Calling it with lines set to ["a", "b", "c", "d", "e"] (newlines written as \n):
| n | result |
|---|---|
| -2 | "a\nb\nc" |
| -1 | "a\nb\nc\nd" |
| -4 | "a" |
| -5 | "" |
| -9 | "" |
| 0 | "" |
| 2 | "a\nb" |
| 9 | "a\nb\nc\nd\ne" |
An empty list gives "" for n = -3 and for n = 3.
Kotlin details worth knowing
- Delayed initialization of a
val.val end: Intfollowed by one assignment in each branch of anif/elsecompiles. A second assignment on the same path, or a path that skips the assignment, would be a compile error. ifis also an expression. You could writeval end = if (n < 0) maxOf(0, lines.size + n) else minOf(n, lines.size), with the same behaviour. The lesson uses the statement form so each branch is its own step.maxOfandminOfare mirrors.maxOf(0, x)puts a floor underx;minOf(n, size)puts a ceiling overn.- The extreme value is safe.
n = Int.MIN_VALUEgiveslines.size + n, a large negative number that doesn't overflow whenlines.sizeis not negative.maxOfturns it into 0 and the result is"". - A built-in exists.
lines.dropLast(2)returns all items except the last 2, and gives an empty list when you drop more than there are. The lesson builds the end index by hand so you see how the pieces fit.
Edge cases and common mistakes
- Passing a negative
ntosubList. It throws, because the end index can't be negative. Computelines.size + nfirst. - Forgetting the floor at 0. With 5 lines and
n = -9,lines.size + nis-4, andsubList(0, -4)throws.maxOf(0, ...)prevents it. - The boundary
n = -lines.size. With 5 lines andn = -5,endis 0 and the result is"". One step less,n = -4, keeps a single line. - Subtracting instead of adding.
nis already negative, solines.size + nis the right sum;lines.size - nwould go past the end of the list. n = 0is not negative. It takes the second branch and gives"", not the whole list.- Empty input. An empty list gives
""for anyn.
