Start learning free

LESSON 5 OF 70 · PROJECTS: COMMAND-LINE TOOLS

head v1 in Kotlin: The First 10 Lines with subList

Practice Read the full explanation

Build a tiny version of the Unix head command. Given a list of lines, return the first 10 lines joined by newline characters (\n). If the input has fewer than 10 lines, return all of them. If there are no lines at all, return the empty string.

Function signature:

fun head(lines: List<String>): String

Example:

Input: lines = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"]

Output: "a\nb\nc\nd\ne\nf\ng\nh\ni\nj"

When printed:
a
b
c
d
e
f
g
h
i
j

Use List.subList(fromIndex, toIndex) to grab the first 10 lines, but cap toIndex at lines.size when the list is shorter than 10. Then joinToString("\n").

Compute val end = minOf(10, lines.size), then call lines.subList(0, end).

The full solution:
class Solution {
    fun head(lines: List<String>): String {
        val end = minOf(10, lines.size)
        return lines.subList(0, end).joinToString("\n")
    }
}

STEP 1 OF 2
    Ctrl + Enter to check

    KOTLIN · PROJECTS: COMMAND-LINE TOOLS

    Head V1 in Kotlin, explained

    Problem overview

    The Unix head command prints the beginning of a file, ten lines by default. In this first version you write it as a function: fun head(lines: List<String>): String. It returns the first 10 lines joined by newline characters (\n). If the list has fewer than 10 lines, you return all of them, and an empty list gives an empty string.

    With the thirteen lines "a" to "m", the result is "a\nb\nc\nd\ne\nf\ng\nh\ni\nj": the first ten letters, with a newline between each two and none after j.

    Approach

    You need two pieces: a way to cut the first ten items out of a list, and a way to glue them into one string. Gluing is joinToString("\n"), which puts a separator between each two items and none at the ends. Cutting is subList(fromIndex, toIndex), which returns the items from fromIndex up to, but not including, toIndex.

    The catch is lists shorter than 10. subList refuses to go past the end of the list, so asking for subList(0, 10) on a three-line list throws an exception. The fix is to compute the end first: the smaller of 10 and the list's size.

    Step by step

    1. Compute val end = minOf(10, lines.size). minOf returns the smaller of its two arguments. For 13 lines end is 10, for 3 lines it is 3, and for an empty list it is 0. So end never goes past the size.
    2. Take the sublist and join it. lines.subList(0, end) holds the lines at positions 0 up to end - 1, and joinToString("\n") turns them into the result. Since end is always valid, even an empty list works: subList(0, 0) is an empty list and joins to "".

    The solution in Kotlin

    class Solution {
        fun head(lines: List<String>): String {
            val end = minOf(10, lines.size)
            return lines.subList(0, end).joinToString("\n")
        }
    }
    

    Calling it on a few inputs (newlines written as \n):

    linesresult
    13 lines, "a" to "m""a\nb\nc\nd\ne\nf\ng\nh\ni\nj"
    ["x", "y", "z"]"x\ny\nz"
    exactly 10 lines, "a" to "j""a\nb\nc\nd\ne\nf\ng\nh\ni\nj"
    11 lines, "a" to "k""a\nb\nc\nd\ne\nf\ng\nh\ni\nj"
    []""

    Kotlin details worth knowing

    • The end index is exclusive. subList(0, 10) returns positions 0 to 9, which is exactly ten items. You don't write end - 1.
    • subList checks its range. On a list of 13 items, subList(0, 20) throws an IndexOutOfBoundsException with the message toIndex = 20. That's why the lesson clamps the end with minOf instead of passing 10 straight in.
    • minOf is a plain function. You call it as minOf(a, b); no import is needed.
    • The result is a String, not a list. joinToString returns text, so the function's return type matches without any conversion.
    • A built-in alternative exists. lines.take(10) returns at most the first 10 items and never throws, so lines.take(10).joinToString("\n") gives the same results as above. The lesson spells out the clamping so the idea is visible; the next version builds on it.

    Edge cases and common mistakes

    • Fewer than 10 lines. Writing lines.subList(0, 10) directly works for 13 lines and crashes for 3. Always clamp.
    • Exactly 10 lines. end is 10 and every line is kept.
    • An empty list. end is 0, the sublist is empty and the result is "", with no special case in the code.
    • An off-by-one end. subList(0, 9) gives nine lines, and subList(0, 11) asks for an eleventh.
    • A trailing newline. Joining with a separator leaves nothing after the last line. Appending "\n" after every line would not match the expected text.

    Try the cases in the table 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