Start learning free

LESSON 8 OF 70 · PROJECTS: COMMAND-LINE TOOLS

head v4 in Kotlin: Negative n Drops the Tail

Practice Read the full explanation

Same signature as v2/v3, but now n may be negative. Real head -n -K prints all lines except the last K. So when n < 0 return all lines except the last |n|; when n ≥ 0 behave exactly like v3 (return the first n, capped at the input length). If |n| is at least the number of lines, nothing is left, so return the empty string.

Function signature:

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

Example (negative n):

Input: lines = ["a", "b", "c", "d", "e"], n = -2

Output: "a\nb\nc"

When printed:
a
b
c

Kotlin's subList needs an explicit, non-negative end index. Branch on the sign of n: when n < 0, the end index is lines.size + n; otherwise it's minOf(n, lines.size). Don't forget maxOf(0, ...) for the negative branch in case |n| exceeds the list length.

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")


The full solution:
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")
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    KOTLIN · PROJECTS: COMMAND-LINE TOOLS

    Head V4 in Kotlin, explained

    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 first n lines, 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 keep lines.size + n lines. With 5 lines and n = -2 that is 3. If |n| is bigger than the list, the sum goes below zero, so clamp it at 0 with maxOf.

    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

    1. Declare val end: Int with no value. Kotlin allows a val without 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.
    2. Write the if/else: n < 0 on one side and every other n on the other.
    3. Negative branch: end = maxOf(0, lines.size + n). maxOf returns the larger of its arguments, so the result never drops below 0.
    4. Other branch: end = minOf(n, lines.size), the cap from the previous version.
    5. Return lines.subList(0, end).joinToString("\n"). Both branches have set end, 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):

    nresult
    -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: Int followed by one assignment in each branch of an if/else compiles. A second assignment on the same path, or a path that skips the assignment, would be a compile error.
    • if is also an expression. You could write val 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.
    • maxOf and minOf are mirrors. maxOf(0, x) puts a floor under x; minOf(n, size) puts a ceiling over n.
    • The extreme value is safe. n = Int.MIN_VALUE gives lines.size + n, a large negative number that doesn't overflow when lines.size is not negative. maxOf turns 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 n to subList. It throws, because the end index can't be negative. Compute lines.size + n first.
    • Forgetting the floor at 0. With 5 lines and n = -9, lines.size + n is -4, and subList(0, -4) throws. maxOf(0, ...) prevents it.
    • The boundary n = -lines.size. With 5 lines and n = -5, end is 0 and the result is "". One step less, n = -4, keeps a single line.
    • Subtracting instead of adding. n is already negative, so lines.size + n is the right sum; lines.size - n would go past the end of the list.
    • n = 0 is not negative. It takes the second branch and gives "", not the whole list.
    • Empty input. An empty list gives "" for any n.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free