Problem overview
Real head accepts a count, as in head -n 3. In this version the count becomes a parameter: fun head(lines: List<String>, n: Int): String returns the first n lines joined by newline characters (\n). You may assume 0 <= n <= lines.size, and n = 0 gives an empty string.
For ["alpha", "beta", "gamma", "delta", "epsilon"] and n = 3 the result is "alpha\nbeta\ngamma".
Approach
The previous version fixed the count at 10 and had to guard against lists shorter than that. Here the problem promises that n never exceeds the number of lines, so the guard isn't needed. Cut the first n items with subList(0, n), which takes the positions from 0 up to but not including n, and join them with "\n". The whole function is one expression.
Why there is no clamping here
A function that trusts its caller can be shorter, but the promise has to be real. The lesson states the range, 0 <= n <= lines.size, so the call can't ask for lines that aren't there. If the promise were dropped, you would need the same safeguard as before: use the smaller of n and the number of lines as the end index. Negative values would need their own thought too, because a negative end index is not "count from the back" in subList.
Step by step
- Return
lines.subList(0, n).joinToString("\n"). The sublist holds exactlynlines, and the join puts a newline between each two of them. Withn = 0the sublist is empty and the join gives"".
The solution in Kotlin
class Solution {
fun head(lines: List<String>, n: Int): String {
return lines.subList(0, n).joinToString("\n")
}
}
Calling it on ["alpha", "beta", "gamma", "delta", "epsilon"] and on an empty list (newlines written as \n):
| lines | n | result |
|---|---|---|
| the five words | 3 | "alpha\nbeta\ngamma" |
| the five words | 1 | "alpha" |
| the five words | 5 | "alpha\nbeta\ngamma\ndelta\nepsilon" |
| the five words | 0 | "" |
[] | 0 | "" |
Kotlin details worth knowing
- The end index is exclusive.
subList(0, n)returns exactlynitems, soncan be passed straight through. subListis strict about its range. With five lines,head(lines, 6)throws anIndexOutOfBoundsExceptionwith the messagetoIndex = 6, andhead(lines, -1)throws anIllegalArgumentExceptionwith the messagefromIndex(0) > toIndex(-1). The lesson's tests stay inside the promised range, so neither happens there.subListis a view, not a copy. It shows the same items as the original list. For aMutableListmholding"a", "b", "c", afterval sub = m.subList(0, 2)andm[0] = "Z",subprints as[Z, b]. Here that doesn't matter, because the sublist is joined into a new string at once.take(n)is the forgiving version.lines.take(n)returns at most the firstnitems and doesn't throw when the list is shorter.subListis the stricter choice, which fits a lesson that promisesnis in range.
Edge cases and common mistakes
n = 0.subList(0, 0)is empty and the result is"". No special case is needed.nequal to the size. The sublist is the whole list, so every line comes back.- Confusing the end index with the last position. The second argument is one past the last item you want.
subList(0, n - 1)returns one line too few. - Dropping the separator.
joinToString()with no argument joins with", ", which givesalpha, beta, gammainstead of lines. - Going out of range. Passing an
nlarger than the list throws. This version doesn't guard against it because the lesson promises it can't happen.
Try the table's inputs in the editor above.
