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, keepmin(n, lines.count)lines, as before. - For
n < 0, walk back from the end: keeplines.count + nlines. With 5 lines andn = -2that is 3. Becausenis 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
- Declare
endwith a type and no value:let end: Int. The type is needed because there is no value yet to infer it from. - Split the two cases with an
if n < 0and anelse. - Negative
n: assignend = max(0, lines.count + n).maxreturns the larger of its two arguments, so the count can't fall below 0. - Non-negative
n: assignend = min(n, lines.count), the cap from the previous version. - Slice and join. After the
if/else,endis set whichever branch ran, solines[0..<end]andjoined(separator: "\n")work for either sign ofn.
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
letwithout a value.let end: Intdeclares a constant that is assigned later. Swift accepts this when every path assigns it exactly once before it is read. Here each branch of theif/elseassigns it once, soendstays a constant even though two different expressions can set it. - Why not
var? Avarwould also work, butlettells the reader thatendnever changes after the branch. maxmirrorsmin.mincaps a value from above andmax(0, ...)floors it from below. The two together keependinside0...lines.countin every case, which is what makes the slice safe.- Adding a negative number.
lines.count + nwith a negativenis subtraction, and it needs noabsor 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 = -5givesend = 0and the result is"".|n|larger than the count.n = -9would give a negative count without themax, 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 negativendrops lines from the end.- An empty array.
head([], -3)andhead([], 3)are both"". - Sign mix-ups.
lines.count - nwith a negativenadds to the count and goes past the array. The sum must belines.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" |
