Start learning free

LESSON 6 OF 71 · PROJECTS: COMMAND-LINE TOOLS

head -n in Swift: Taking the First n Lines

Practice Read the full explanation

Extend your head command to take an integer n and return the first n lines of lines, joined by newline characters (\n). For this version you may assume 0 ≤ n ≤ lines.count. If n is 0 the result is the empty string.

Function signature:

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

Example:

Input: lines = ["alpha", "beta", "gamma", "delta", "epsilon"], n = 3

Output: "alpha\nbeta\ngamma"

When printed:
alpha
beta
gamma

Use the slice lines[0..<n] for the first n elements, then joined(separator: "\n"). Since the problem guarantees n ≤ lines.count, no min needed.

Combine the slice and join into one expression:
return lines[0..<n].joined(separator: "\n")


The full solution:
class Solution {
    func head(_ lines: [String], _ n: Int) -> String {
        return lines[0..<n].joined(separator: "\n")
    }
}

STEP 1 OF 1
    Ctrl + Enter to check

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Head V2 in Swift, explained

    Problem overview

    The first version of head always returned up to 10 lines. This version adds the count as a parameter: head(_ lines: [String], _ n: Int) -> String returns the first n lines joined by newline characters. For this version you may assume 0 <= n <= lines.count. When n is 0 the result is the empty string.

    For ["alpha", "beta", "gamma", "delta", "epsilon"] and n = 3 the result is "alpha\nbeta\ngamma". Printed, those are three lines.

    Approach

    The function from the previous version computed how many lines to keep. Here the caller supplies that number, and the promise that it lies between 0 and the number of lines means the function can use it directly as the end of the range. There is nothing to compute, so the body is a slice and a join.

    The next version builds on this one by relaxing the assumption.

    Step by step

    1. Slice and join in one return. lines[0..<n] selects the first n items, from index 0 up to but not including index n. Calling joined(separator: "\n") on that slice puts a newline between each two lines and none at the end.

    The solution in Swift

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

    Swift details worth a closer look:

    • The unlabeled parameters. Both parameters have an underscore in front, so a call looks like head(lines, 3), not head(lines, n: 3). The first _ hides the label of lines and the second does the same for n.
    • The half-open range 0..<n contains exactly n positions, so it selects n lines. For n = 0 it is the empty range 0..<0, a valid range that selects nothing, and joining nothing gives "".
    • The result of the subscript is an ArraySlice. It keeps the indices of the original array. A slice taken from positions 2 up to 4 has startIndex 2 and endIndex 4, and its first element is read with slice[2], not slice[0]. Here the slice starts at 0, so the difference doesn't show, and joined doesn't use indices anyway.
    • Invalid ranges crash. Swift checks the range at run time. An n larger than lines.count stops the program with a fatal error, and so does a negative n, because the range 0..<n would then have its upper bound below its lower bound. The assumption in the statement is what keeps this function safe.

    Complexity

    The function joins n lines, so the time is proportional to the total length of those lines. The slice itself isn't a copy, and the only new memory is the result string.

    Edge cases and common mistakes

    • n = 0. The result is "", not a string holding a newline. head(lines, 0) works without a special case.
    • n equal to the count. Every line is returned. head(["a", "b"], 2) is "a\nb".
    • Using a closed range. lines[0...n] returns n + 1 lines and crashes when n equals the count.
    • Joining with a trailing newline. The separator goes between lines only, so the result never ends with \n.

    Testing

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