Problem overview
This version of head accepts a negative n. The signature is head(lines: List[String], n: Int): String, with the lines back in a List. Real head -n -K prints all lines except the last K, and this function follows it. For n < 0 it returns every line except the last |n|. For n >= 0 it behaves as before: the first n lines, capped at the number of lines. When |n| is at least the number of lines, nothing is left and the result is the empty string.
For ["a", "b", "c", "d", "e"] and n = -2, the last two lines are dropped and the result is "a\nb\nc".
Approach
Both cases can be reduced to one question: how many lines from the front should be kept? Call that number end. Then the answer is always lines.take(end).mkString("\n").
For a non-negative n, end is the smaller of n and the number of lines, exactly as in the capping version. For a negative n, dropping the last |n| lines means keeping lines.size + n of them. With five lines and n = -2, that is 5 + (-2) = 3. Adding a negative number subtracts, so no absolute value is needed.
That count can go below zero: with five lines and n = -9, 5 + (-9) is -4. A count of lines can't be negative, so it is raised to 0 with math.max(0, ...). Then end always lies between 0 and the number of lines, and the result is empty when everything is dropped.
In Scala, if/else is an expression: it produces a value, so the choice between the two formulas can be written directly on the right of val end =.
Step by step
- Compute
endwith one if/else expression. Whenn < 0, it ismath.max(0, lines.size + n). Otherwise it ismath.min(n, lines.size).math.maxis the mirror ofmath.min. - Take and join.
lines.take(end).mkString("\n")keeps the firstendlines and joins them with newlines. This is the last expression of the method, so it is the returned value.
The solution in Scala
class Solution {
def head(lines: List[String], n: Int): String = {
val end = if (n < 0) math.max(0, lines.size + n) else math.min(n, lines.size)
lines.take(end).mkString("\n")
}
}
Details worth knowing:
- Both branches of the
if/elseareIntvalues, soendis anInt. Anifwithout anelsehas no value in the other case, so forval end = ...theelseis required. lines.size + nis ordinaryIntaddition. Here it can't overflow:lines.sizeis never negative, and a negativenonly moves the sum down.takedoesn't fail for a count outside the list.List("a", "b", "c").take(10)returns all three items, andtake(0)returns an empty list. In this solution themaxandminmakeendvalid anyway, so the code doesn't lean on that.- A
Listhas the methoddropRight(k), which removes the lastkitems.List("a", "b", "c", "d", "e").dropRight(2).mkString("\n")gives"a\nb\nc", the same as this lesson's answer forn = -2. The lesson computes the count by hand instead, which also handlesn >= 0in the same expression.
Edge cases and common mistakes
n = -1. Only the last line is dropped: for the five lines above the result is"a\nb\nc\nd".|n|equal to the length.n = -5givesend = 0and the result"".|n|larger than the length.n = -9would give-4without themax. With it,endis 0 and the result is"".n = 0. The non-negative branch givesend = 0, so the result is"". Zero is not "drop nothing".nlarger than the length.n = 9is capped at 5 and returns all five lines.- An empty list.
head(List(), -3)gives"", as does any non-negativen. - Using the wrong sign.
lines.size - nwith a negativenadds|n|, which would keep more lines than exist instead of fewer. - Testing the wrong branch. Use
n < 0, notn <= 0. With<=,n = 0would go to the first formula,math.max(0, lines.size + 0), and return every line instead of none.
Testing
With e as the list ["a", "b", "c", "d", "e"]:
| Call | Result |
|---|---|
head(e, -2) | "a\nb\nc" |
head(e, -1) | "a\nb\nc\nd" |
head(e, -5) | "" |
head(e, -9) | "" |
head(e, 0) | "" |
head(e, 3) | "a\nb\nc" |
head(e, 9) | "a\nb\nc\nd\ne" |
head(List(), -3) | "" |
