Start learning free

LESSON 8 OF 69 · PROJECTS: COMMAND-LINE TOOLS

head v4 in Go: 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:

func head(lines []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

Branch on the sign of n with an early return. When n < 0, slice up to max(0, len(lines)+n) (the max floors a too-large |n|); otherwise slice up to min(len(lines), n). Stitch the slice with strings.Join(..., "\n").

if n < 0 {
    return strings.Join(lines[:max(0, len(lines)+n)], "\n")
}
return strings.Join(lines[:min(len(lines), n)], "\n")


The full solution:
func head(lines []string, n int) string {
    if n < 0 {
        return strings.Join(lines[:max(0, len(lines)+n)], "\n")
    }
    return strings.Join(lines[:min(len(lines), n)], "\n")
}

STEP 1 OF 3
    Ctrl + Enter to check

    GO · PROJECTS: COMMAND-LINE TOOLS

    Head V4 in Go, explained

    Problem overview

    Version 4 of the head tool gives negative values of n a meaning, the same one the real head -n -K has: print all lines except the last K. The signature is still head(lines []string, n int) string. For n < 0, the function returns all the lines except the last |n|. For n >= 0 it behaves like version 3: the first n lines, capped at the input length. When |n| is at least the number of lines, nothing is left and the result is the empty string.

    For ["a", "b", "c", "d", "e"] and n = -2 the result is "a\nb\nc".

    Approach: one end index for each case

    Both cases are the same operation, take the lines from the start up to some end index. Only the way the end is computed differs. For a non-negative n it is min(len(lines), n), as in the previous version. For a negative n, dropping |n| lines from the tail means keeping len(lines) + n lines, because adding a negative number subtracts. With 5 lines and n = -2, that is 3.

    That value can fall below zero when more lines are dropped than exist, and a negative end isn't a valid slice bound. Taking max(0, len(lines) + n) stops the count at 0, which yields an empty slice and so the empty string.

    Step by step

    1. Open an if for n < 0, since a negative count needs its own calculation.
    2. Return the first max(0, len(lines)+n) lines joined with strings.Join(..., "\n"). The max is the guard against a negative bound.
    3. After the if, return the first min(len(lines), n) lines joined the same way. Only a non-negative n gets here, because the if already returned for negative values.

    The solution in Go

    func head(lines []string, n int) string {
        if n < 0 {
            return strings.Join(lines[:max(0, len(lines)+n)], "\n")
        }
        return strings.Join(lines[:min(len(lines), n)], "\n")
    }
    

    The Go details:

    • Early return instead of else. After the if block returns, the code below it runs only for non-negative n. Go style prefers this to an else that wraps the rest of the function.
    • Built-in min and max. Both are built in since Go 1.21, so Go 1.22 needs no helpers. They are mirror images, and each of the two returns guards one side of the valid range.
    • Both ends clamp. The negative branch uses max to stay at or above 0, and the other branch uses min to stay at or below the length. Together they keep every slice bound inside [0, len(lines)].
    • The result of lines[:end] shares the original array. It isn't a copy, which is fine because strings.Join only reads it.

    Tracing

    These inputs and results come from running the function with the five lines a to e (shown as Go string literals):

    n = -2  ->  "a\nb\nc"
    n = -1  ->  "a\nb\nc\nd"
    n = -5  ->  ""
    n = -9  ->  ""
    n = 0   ->  ""
    n = 3   ->  "a\nb\nc"
    n = 99  ->  "a\nb\nc\nd\ne"
    nil, n = -1  ->  ""
    

    The rows for n = -5 and n = -9 show the clamp: len(lines) + n is 0 and -4, and both become an empty slice.

    Edge cases and common mistakes

    • Dropping more lines than exist. Without max(0, ...), n = -9 gives the bound -4 and the program panics.
    • Dropping exactly all lines. n = -5 gives a bound of 0, an empty slice and an empty string.
    • Zero is not negative. n = 0 takes the second branch and returns the empty string, while a negative n of any size never returns all the lines.
    • Subtracting the wrong way. Writing len(lines) - n with a negative n gives a bound past the end, which panics. The sum len(lines) + n is the right one, as n is already negative.
    • An empty input. With no lines the bound is 0 for any n below zero, so the result is "".
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free