Start learning free

LESSON 7 OF 70 · PROJECTS: COMMAND-LINE TOOLS

head v3 in Kotlin: Cap n at lines.size

Practice Read the full explanation

Same signature as v2, but now n may be larger than the number of lines. If n > lines.size simply return all the lines (don't crash, don't pad). For this version assume n ≥ 0. If n is 0, or there are no lines, the result is the empty string.

Function signature:

fun head(lines: List<String>, n: Int): String

Example:

Input: lines = ["alpha", "beta", "gamma"], n = 10

Output: "alpha\nbeta\ngamma"

When printed:
alpha
beta
gamma

lines.subList(0, n) with n > lines.size throws. So clamp n with minOf(n, lines.size) first.

val 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 = minOf(n, lines.size)
        return lines.subList(0, end).joinToString("\n")
    }
}

STEP 1 OF 2
    Ctrl + Enter to check

    KOTLIN · PROJECTS: COMMAND-LINE TOOLS

    Head V3 in Kotlin, explained

    Problem overview

    The signature is the same as in the previous version, fun head(lines: List<String>, n: Int): String, but n may now be larger than the number of lines. When it is, return all the lines: don't crash and don't pad. You can assume n >= 0. If n is 0, or there are no lines, the result is the empty string.

    For ["alpha", "beta", "gamma"] and n = 10 the result is "alpha\nbeta\ngamma": all three lines, with newlines between them only.

    Approach

    The previous version passed n straight to subList(0, n), which is only legal when n is at most the size of the list. With a larger n the call throws an IndexOutOfBoundsException. The fix is the one you've seen in the version that kept the first 10 lines: don't use n as the end index directly. Use the smaller of n and lines.size. That index is always inside the list, so subList never complains.

    Step by step

    1. Compute val end = minOf(n, lines.size). With 5 lines and n = 8 it is 5, and with n = 3 it is 3. You never ask for more lines than exist.
    2. Return lines.subList(0, end).joinToString("\n"). The sublist is always valid, the join puts a newline between each two lines, and an empty sublist joins to an empty string.

    The solution in Kotlin

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

    Calling it with lines set to ["alpha", "beta", "gamma"] (newlines written as \n):

    nresult
    10"alpha\nbeta\ngamma"
    3"alpha\nbeta\ngamma"
    2"alpha\nbeta"
    0""
    Int.MAX_VALUE"alpha\nbeta\ngamma"

    An empty list with n = 4 also gives "": end is 0 and the sublist is empty.

    Kotlin details worth knowing

    • minOf takes any two comparable values. Here both are Int, so end is an Int and Kotlin infers the type; no annotation is needed.
    • Huge values are fine. Nothing is added to n, so even Int.MAX_VALUE can't overflow. The call just picks lines.size.
    • val with a one-line initializer. end is assigned once, where it is declared. The next version needs a different shape, because end will be computed in two different ways.
    • Negative values still fail. This version assumes n >= 0. With n = -1, end is -1 and subList throws an IllegalArgumentException with the message fromIndex(0) > toIndex(-1).

    Clamping against checking

    You could also write an if that returns early when n is at least the size, and call subList only otherwise. Clamping is shorter and has no special case: one number, end, is correct in every situation, and the rest of the function never has to ask whether the input was too big. Whenever a value feeds an index, computing a safe index first is often cleaner than guarding each call.

    Edge cases and common mistakes

    • n bigger than the list. This is the case the version exists for. Without the clamp, subList throws.
    • Using maxOf by mistake. maxOf(n, lines.size) is never smaller than the size, so it always asks for too much when n is large, and it ignores a smaller n.
    • n equal to the size. The sublist is the whole list, and nothing is cut.
    • Padding the result. For n = 10 and three lines you get three lines, not ten with blanks at the end.
    • Empty input. No lines, or n = 0, gives "".
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free