Start learning free

LESSON 8 OF 70 · PROJECTS: COMMAND-LINE TOOLS

head -n -K in TypeScript: Negative n with slice

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:

head(lines: string[], n: number): string

Example (negative n):

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

Output: "a\nb\nc"

When printed:
a
b
c

TypeScript's slice(0, n) already does the right thing for both signs. A negative end index means "stop that many from the end".

The full solution is the same one-liner from v2/v3:
class Solution {
    head(lines: string[], n: number): string {
        return lines.slice(0, n).join("\n");
    }
}

STEP 1 OF 1
    Ctrl + Enter to check

    TYPESCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Head V4 in TypeScript, explained

    Problem overview

    Version 4 of head lets n be negative, as the real head -n -K does: it prints all lines except the last K. The signature stays head(lines: string[], n: number): string. For n >= 0 the function behaves as before, returning the first n lines capped at the input length. For n < 0 it returns all lines except the last |n|. 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: a negative end index counts from the end

    You might expect to need an if that treats the two signs separately: for a negative n, compute lines.length + n and slice up to that. That arithmetic is exactly what slice does for you. When the end argument is negative, slice counts it back from the end of the array, so slice(0, -2) means "from the start, stopping 2 items before the end". The array's length is added to the negative index, and the result is clamped to 0 if it would go below it.

    So lines.slice(0, n) already gives the right answer for both signs. With five lines and n = -2 the end index works out to 3, and the slice holds the items at indexes 0, 1 and 2.

    Step by step

    1. Return lines.slice(0, n).join("\n"). It is the same line as in the two previous versions. What the lesson adds is the reason it works for a negative n: a negative end stops that many items before the end of the array.

    The solution in TypeScript

    class Solution {
        head(lines: string[], n: number): string {
            return lines.slice(0, n).join("\n");
        }
    }
    
    • A negative end index is not an error in slice. It is a count from the end: -1 means "up to the last item, not including it".
    • If the count is larger than the array, the end becomes 0 and the slice is empty. For five lines, n = -10 and n = -5 both give "".
    • For a positive n larger than the array, the end is capped at the length, so all lines come back. The same call covers every case in the statement.
    • Indexing with a negative number does not work this way: lines[-1] is undefined in JavaScript. Counting from the end is a feature of slice, not of arrays in general.

    Complexity

    Time and space are proportional to the number of lines kept, because slice copies them and join builds the string. Dropping lines at the end costs nothing, since they are never visited.

    Edge cases and common mistakes

    • n = -1. Only the last line is dropped: on five lines the result has the first four.
    • |n| equal to the length. Nothing remains, so the result is "". This holds for n = -5 on five lines.
    • |n| larger than the length. n = -10 on five lines also gives "", not an error.
    • n = 0. The result is "", because slice(0, 0) is empty. Zero is not treated as "drop nothing".
    • Mixing up the two meanings. A positive n keeps the first n lines, and a negative n drops the last |n|. They are not mirror images: n = 2 and n = -2 on five lines give two lines and three lines.
    • Empty list. Every n gives "".

    Testing

    InputResult
    ["a", "b", "c", "d", "e"], n = -2"a\nb\nc"
    ["alpha", "beta", "gamma", "delta", "epsilon"], n = -1"alpha\nbeta\ngamma\ndelta"
    the same five lines, n = -5""
    the same five lines, n = -10""
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free