Start learning free

LESSON 8 OF 71 · PROJECTS: COMMAND-LINE TOOLS

head -n -K in Swift: Dropping the Last Lines

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

Swift's range slice needs an explicit, non-negative end index. Branch on the sign of n: when n < 0, the end index is lines.count + n; otherwise it's min(n, lines.count). Don't forget max(0, ...) for the negative branch in case |n| exceeds the array length.

let end: Int
if n < 0 {
    end = max(0, lines.count + n)
} else {
    end = min(n, lines.count)
}
return lines[0..<end].joined(separator: "\n")


The full solution:
class Solution {
    func head(_ lines: [String], _ n: Int) -> String {
        let end: Int
        if n < 0 {
            end = max(0, lines.count + n)
        } else {
            end = min(n, lines.count)
        }
        return lines[0..<end].joined(separator: "\n")
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Head V4 in Swift, explained

    Problem overview

    The signature stays head(_ lines: [String], _ n: Int) -> String, but now n can be negative. In the real head, -n -K prints every line except the last K. So for n < 0 the function returns all lines except the last |n|, and for n >= 0 it returns the first n lines, capped at the input length. 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 and three remain.

    Approach

    Both cases can be reduced to the same question: how many lines from the start should be kept? Call that number end, and the answer is always lines[0..<end].

    • For n >= 0, keep min(n, lines.count) lines, as before.
    • For n < 0, walk back from the end: keep lines.count + n lines. With 5 lines and n = -2 that is 3. Because n is negative, adding it subtracts |n|.

    The negative case needs a floor at 0. With 5 lines and n = -9, the sum would be -4, which isn't a valid count. max(0, lines.count + n) turns it into 0, so the result is empty, as the lesson requires.

    Step by step

    1. Declare end with a type and no value: let end: Int. The type is needed because there is no value yet to infer it from.
    2. Split the two cases with an if n < 0 and an else.
    3. Negative n: assign end = max(0, lines.count + n). max returns the larger of its two arguments, so the count can't fall below 0.
    4. Non-negative n: assign end = min(n, lines.count), the cap from the previous version.
    5. Slice and join. After the if/else, end is set whichever branch ran, so lines[0..<end] and joined(separator: "\n") work for either sign of n.

    The solution in Swift

        func head(_ lines: [String], _ n: Int) -> String {
            let end: Int
            if n < 0 {
                end = max(0, lines.count + n)
            } else {
                end = min(n, lines.count)
            }
            return lines[0..<end].joined(separator: "\n")
        }
    

    Swift details worth a closer look:

    • A let without a value. let end: Int declares a constant that is assigned later. Swift accepts this when every path assigns it exactly once before it is read. Here each branch of the if/else assigns it once, so end stays a constant even though two different expressions can set it.
    • Why not var? A var would also work, but let tells the reader that end never changes after the branch.
    • max mirrors min. min caps a value from above and max(0, ...) floors it from below. The two together keep end inside 0...lines.count in every case, which is what makes the slice safe.
    • Adding a negative number. lines.count + n with a negative n is subtraction, and it needs no abs or sign flip.

    Complexity

    The function does a constant amount of work to compute end, then joins at most lines.count lines. Time is proportional to the total length of the lines kept. The slice isn't a copy, so the extra space is the result string.

    Edge cases and common mistakes

    • |n| equal to the count. With five lines, n = -5 gives end = 0 and the result is "".
    • |n| larger than the count. n = -9 would give a negative count without the max, and the range would crash. With it, the result is "".
    • n = -1. It drops only the last line: "a\nb\nc\nd" for the five-line example.
    • n = 0. It takes the non-negative branch and returns "", which is not the same as dropping zero lines. Only a negative n drops lines from the end.
    • An empty array. head([], -3) and head([], 3) are both "".
    • Sign mix-ups. lines.count - n with a negative n adds to the count and goes past the array. The sum must be lines.count + n.

    Testing

    Input (["a", "b", "c", "d", "e"])Result (as a Swift literal)
    n = -2"a\nb\nc"
    n = -1"a\nb\nc\nd"
    n = -5""
    n = -9""
    n = 0""
    n = 2"a\nb"
    n = 9"a\nb\nc\nd\ne"
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free