Start learning free

LESSON 380 OF 415 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: head v3 — Cap n at lines.count in Swift

Practice

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

    Head V3 in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free