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
- Compute the cap.
val end = math.min(n, lines.length)is the smaller ofnand the number of lines. - Slice and join. Return
lines.slice(0, end).mkString("\n"), as in the previous version but withendin place ofn.
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.mincomes fromscala.math, which is available asmathwithout an import. It returns the smaller of two numbers of the same type, here twoIntvalues.- Even a huge
nis safe:head(g, 2147483647), with2147483647the largestInt, caps at 5 for the five-line array and returns all five lines. The cap is computed before any slicing, so the size ofndoesn't matter. valmakesenda 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, soreturncould be left out.
Edge cases and common mistakes
nlarger than the length.head(Array("alpha", "beta", "gamma"), 10)gives"alpha\nbeta\ngamma". No padding, no error.nequal to the length. The cap changes nothing, and every line comes back.n = 0.endis 0, the slice is empty, and the result is"".- An empty array.
head(Array[String](), 4)gives"", sinceendismin(4, 0) = 0. - Using
maxinstead ofmin.math.max(n, lines.length)is never smaller than the length, so it would ask for more lines than exist. - Looping to
nby index. A hand-written loop from 0 ton - 1that readslines(i)fails with an out-of-bounds exception onceireaches the length. Looping toendavoids this. - Negative
n. The lesson doesn't cover it. With this solution, a negativenbecomes a negativeend, andslice(0, -2)returns an empty array, so the result is"".
Testing
With g as the array ["alpha", "beta", "gamma", "delta", "epsilon"]:
| Call | Result |
|---|---|
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) | "" |
