Start learning free

LESSON 7 OF 70 · PROJECTS: COMMAND-LINE TOOLS

head v3 in Scala: Capping n with math.min

Practice Read the full explanation

Same signature as v2, but now n may be larger than the number of lines. If n > lines.length 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:

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

Example:

Input: lines = ["alpha", "beta", "gamma"], n = 10

Output: "alpha\nbeta\ngamma"

When printed:
alpha
beta
gamma

Compute a capped end with math.min(n, lines.length) so you only take the safe prefix, then join it with newlines.

val end = math.min(n, lines.length)
return lines.slice(0, end).mkString("\n")


The full solution:
class Solution {
    def head(lines: Array[String], n: Int): String = {
        val end = math.min(n, lines.length)
        return lines.slice(0, end).mkString("\n")
    }
}

STEP 1 OF 2
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Head V3 in Scala, explained

    Problem overview

    This version of head keeps the signature head(lines: Array[String], n: Int), but n may now be larger than the number of lines. When it is, the function returns all the lines: it must not crash and must not pad. The lesson assumes n >= 0. For n = 0, or for no lines, the result is the empty string.

    For ["alpha", "beta", "gamma"] and n = 10, the result is "alpha\nbeta\ngamma": three lines, not ten.

    Approach

    The earlier version took lines.slice(0, n) directly, which relied on the promise that n fits. Now that promise is gone, so the function decides how many lines it can actually return: the smaller of n and lines.length. Call that number end.

    With five lines, n = 8 gives end = 5, and n = 3 gives end = 3. In both cases end never goes past the array, so slice(0, end) asks only for lines that exist. Then mkString("\n") joins them as before.

    The cap states the rule in the code: "never more lines than there are". It matters for what the function means, and a learner should write it even where a library call happens to be forgiving. In Scala, slice clamps its range to the array. For the five-line array above, slice(0, 8) already returns all five items, and the capped version returns the same text. The cap makes the intent explicit and keeps the code correct if slice is later swapped for something stricter, such as reading elements one by one by index. Reading g(8) on that array throws an ArrayIndexOutOfBoundsException, which is the failure the cap protects such code from.

    Step by step

    1. Compute the cap. val end = math.min(n, lines.length) is the smaller of n and the number of lines.
    2. Slice and join. Return lines.slice(0, end).mkString("\n"), as in the previous version but with end in place of n.

    The solution in Scala

    class Solution {
        def head(lines: Array[String], n: Int): String = {
            val end = math.min(n, lines.length)
            return lines.slice(0, end).mkString("\n")
        }
    }
    

    Details worth knowing:

    • math.min comes from scala.math, which is available as math without an import. It returns the smaller of two numbers of the same type, here two Int values.
    • Even a huge n is safe: head(g, 2147483647), with 2147483647 the largest Int, caps at 5 for the five-line array and returns all five lines. The cap is computed before any slicing, so the size of n doesn't matter.
    • val makes end a name that can't be reassigned. It is computed once and used once.
    • The method returns its string with return. In Scala the last expression is the result anyway, so return could be left out.

    Edge cases and common mistakes

    • n larger than the length. head(Array("alpha", "beta", "gamma"), 10) gives "alpha\nbeta\ngamma". No padding, no error.
    • n equal to the length. The cap changes nothing, and every line comes back.
    • n = 0. end is 0, the slice is empty, and the result is "".
    • An empty array. head(Array[String](), 4) gives "", since end is min(4, 0) = 0.
    • Using max instead of min. math.max(n, lines.length) is never smaller than the length, so it would ask for more lines than exist.
    • Looping to n by index. A hand-written loop from 0 to n - 1 that reads lines(i) fails with an out-of-bounds exception once i reaches the length. Looping to end avoids this.
    • Negative n. The lesson doesn't cover it. With this solution, a negative n becomes a negative end, and slice(0, -2) returns an empty array, so the result is "".

    Testing

    With g as the array ["alpha", "beta", "gamma", "delta", "epsilon"]:

    CallResult
    head(g, 3)"alpha\nbeta\ngamma"
    head(g, 8)"alpha\nbeta\ngamma\ndelta\nepsilon"
    head(g, 0)""
    head(Array("alpha", "beta", "gamma"), 10)"alpha\nbeta\ngamma"
    head(Array[String](), 4)""
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free