Start learning free

LESSON 6 OF 70 · PROJECTS: COMMAND-LINE TOOLS

head v2 in Kotlin: The First n Lines with subList

Practice Read the full explanation

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.size. If n is 0 the result is the empty string.

Function signature:

fun head(lines: List<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.subList(0, n) for the first n elements, then joinToString("\n"). Since the problem guarantees n ≤ lines.size, no min needed.

Combine the two calls into one:
return lines.subList(0, n).joinToString("\n")


The full solution:
class Solution {
    fun head(lines: List<String>, n: Int): String {
        return lines.subList(0, n).joinToString("\n")
    }
}

STEP 1 OF 1
    Ctrl + Enter to check

    KOTLIN · PROJECTS: COMMAND-LINE TOOLS

    Head V2 in Kotlin, explained

    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

    1. Return lines.subList(0, n).joinToString("\n"). The sublist holds exactly n lines, and the join puts a newline between each two of them. With n = 0 the 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):

    linesnresult
    the five words3"alpha\nbeta\ngamma"
    the five words1"alpha"
    the five words5"alpha\nbeta\ngamma\ndelta\nepsilon"
    the five words0""
    []0""

    Kotlin details worth knowing

    • The end index is exclusive. subList(0, n) returns exactly n items, so n can be passed straight through.
    • subList is strict about its range. With five lines, head(lines, 6) throws an IndexOutOfBoundsException with the message toIndex = 6, and head(lines, -1) throws an IllegalArgumentException with the message fromIndex(0) > toIndex(-1). The lesson's tests stay inside the promised range, so neither happens there.
    • subList is a view, not a copy. It shows the same items as the original list. For a MutableList m holding "a", "b", "c", after val sub = m.subList(0, 2) and m[0] = "Z", sub prints 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 first n items and doesn't throw when the list is shorter. subList is the stricter choice, which fits a lesson that promises n is in range.

    Edge cases and common mistakes

    • n = 0. subList(0, 0) is empty and the result is "". No special case is needed.
    • n equal 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 gives alpha, beta, gamma instead of lines.
    • Going out of range. Passing an n larger 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.

    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free