Start learning free

LESSON 8 OF 70 · PROJECTS: COMMAND-LINE TOOLS

head v4 in Scala: Negative n with an if/else Expression

Practice Read the full explanation

Same signature as v2/v3, but now n may be negative. Real head -n -K prints all lines except the last K. So when n < 0 return all lines except the last |n|; when n ≥ 0 behave exactly like v3 (return the first n, capped at the input length). If |n| is at least the number of lines, nothing is left, so return the empty string.

Function signature:

def head(lines: List[String], n: Int): String

Example (negative n):

Input: lines = ["a", "b", "c", "d", "e"], n = -2

Output: "a\nb\nc"

When printed:
a
b
c

Compute the cut-off with a single if/else expression: when n < 0, the end index is math.max(0, lines.size + n); otherwise it's math.min(n, lines.size). Then take(end) and mkString("\n").

val end = if (n < 0) math.max(0, lines.size + n) else math.min(n, lines.size)
lines.take(end).mkString("\n")


The full solution:
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")
    }
}

STEP 1 OF 2
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Head V4 in Scala, explained

    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

    1. Compute end with one if/else expression. When n < 0, it is math.max(0, lines.size + n). Otherwise it is math.min(n, lines.size). math.max is the mirror of math.min.
    2. Take and join. lines.take(end).mkString("\n") keeps the first end lines 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/else are Int values, so end is an Int. An if without an else has no value in the other case, so for val end = ... the else is required.
    • lines.size + n is ordinary Int addition. Here it can't overflow: lines.size is never negative, and a negative n only moves the sum down.
    • take doesn't fail for a count outside the list. List("a", "b", "c").take(10) returns all three items, and take(0) returns an empty list. In this solution the max and min make end valid anyway, so the code doesn't lean on that.
    • A List has the method dropRight(k), which removes the last k items. List("a", "b", "c", "d", "e").dropRight(2).mkString("\n") gives "a\nb\nc", the same as this lesson's answer for n = -2. The lesson computes the count by hand instead, which also handles n >= 0 in 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 = -5 gives end = 0 and the result "".
    • |n| larger than the length. n = -9 would give -4 without the max. With it, end is 0 and the result is "".
    • n = 0. The non-negative branch gives end = 0, so the result is "". Zero is not "drop nothing".
    • n larger than the length. n = 9 is capped at 5 and returns all five lines.
    • An empty list. head(List(), -3) gives "", as does any non-negative n.
    • Using the wrong sign. lines.size - n with a negative n adds |n|, which would keep more lines than exist instead of fewer.
    • Testing the wrong branch. Use n < 0, not n <= 0. With <=, n = 0 would 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"]:

    CallResult
    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)""
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free