Start learning free

LESSON 7 OF 71 · PROJECTS: COMMAND-LINE TOOLS

head -n in Swift: Capping n with min

Practice Read the full explanation

Same signature as v2, but now n may be larger than the number of lines. If n > lines.count 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:

func head(_ lines: [String], _ n: Int) -> String

Example:

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

Output: "alpha\nbeta\ngamma"

When printed:
alpha
beta
gamma

Slicing a Swift array with lines[0..<n] when n > lines.count traps. So clamp n with min(n, lines.count) first.

let 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 = min(n, lines.count)
        return lines[0..<end].joined(separator: "\n")
    }
}

STEP 1 OF 2
    Ctrl + Enter to check

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Head V3 in Swift, explained

    Problem overview

    The signature is the same as in the previous version, head(_ lines: [String], _ n: Int) -> String, but now n may be larger than the number of lines. In that case the function returns all the lines: it doesn't crash and it doesn't pad. You may assume n >= 0. When n is 0, or there are no lines, the result is "".

    For ["alpha", "beta", "gamma"] and n = 10 the result is "alpha\nbeta\ngamma". Asking for ten lines of a three-line input gives the three that exist.

    Approach

    The previous version used n directly as the end of the slice, which is only valid while n doesn't pass the end of the array. The fix is to clamp: the number of lines to keep is the smaller of n and lines.count. With 5 lines, n = 8 keeps 5 and n = 3 keeps 3. The slice is always inside the array, so the join works for every input.

    Step by step

    1. Clamp the count. Write let end = min(n, lines.count). This is the only new line compared with the fixed-n version, and it is what lets n be as large as the caller likes.
    2. Slice up to end and join. lines[0..<end] followed by joined(separator: "\n") works as before, now with a range that can't go past the array.

    The solution in Swift

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

    Swift details worth a closer look:

    • min works on any comparable values. Both arguments are Int here: n is one, and so is lines.count. The call returns whichever is smaller.
    • Why not check and branch? You could write an if n > lines.count test and handle the two cases separately, but min expresses the clamp in one line and leaves a single code path.
    • The empty range again. If n is 0, or the array is empty, end is 0 and 0..<0 selects nothing. The result is "", with no special case.
    • The assumption still matters. The clamp only protects the upper bound. If n were negative, min would return it unchanged, and the range 0..<n would crash at run time, because Swift doesn't allow a range whose upper bound is below its lower bound. The statement rules this input out for this version.

    Complexity

    The function joins at most lines.count lines, so time is proportional to the total length of the selected lines. The clamp is constant time, and the slice doesn't copy. The extra space is the result string.

    Edge cases and common mistakes

    • n larger than the count. The result is every line. head(["alpha", "beta", "gamma"], 10) is "alpha\nbeta\ngamma", with no padding for the missing lines.
    • n = 0. The result is "".
    • Empty array. head([], 4) is "", since min(4, 0) is 0.
    • Clamping to the wrong value. Using min(n, lines.count - 1) would drop the last line. The range is half-open, so the count itself is the right upper bound.
    • Using max by mistake. max(n, lines.count) goes past the end of the array whenever n is larger, which is the crash the clamp is meant to prevent.

    Testing

    InputResult (as a Swift literal)
    ["alpha", "beta", "gamma"], n = 10"alpha\nbeta\ngamma"
    ["alpha", "beta", "gamma", "delta", "epsilon"], n = 3"alpha\nbeta\ngamma"
    [], n = 4""
    five lines, n = 0""
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free