Start learning free

LESSON 6 OF 70 · PROJECTS: COMMAND-LINE TOOLS

head v2 in Scala: The First n Lines with slice

Practice Read the full explanation

Extend your head command to take an integer n and return the first n lines of lines, joined by newline characters (\n). For this version you may assume 0 ≤ n ≤ lines.length. If n is 0 the result is the empty string.

Function signature:

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

Example:

Input: lines = ["alpha", "beta", "gamma", "delta", "epsilon"], n = 3

Output: "alpha\nbeta\ngamma"

When printed:
alpha
beta
gamma

Use lines.slice(0, n) for the first n elements, then mkString("\n"). Since the problem guarantees n ≤ lines.length, no min needed.

Combine the slice and join into one expression:
return lines.slice(0, n).mkString("\n")


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

STEP 1 OF 1
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Head V2 in Scala, explained

    Problem overview

    This version of head takes the count as a parameter. The function head(lines: Array[String], n: Int) returns the first n lines of lines joined by newline characters (\n). The lesson guarantees 0 <= n <= lines.length, and for n = 0 the result is the empty string.

    For ["alpha", "beta", "gamma", "delta", "epsilon"] and n = 3, the result is "alpha\nbeta\ngamma".

    Notice the new parameter type: the lines now arrive as an Array[String] instead of a List[String]. The previous version took a list.

    Approach

    As before, the job has two parts: pick the lines, then join them with mkString("\n"). What changes is how the lines are picked. Instead of a fixed 10, the caller says how many.

    The lesson uses slice(from, until). It returns the items from index from up to, but not including, index until. So lines.slice(0, n) is the items at indices 0, 1, up to n - 1: exactly the first n. For n = 3 that is alpha, beta, gamma. For n = 0 the range is empty, so the slice is empty and mkString gives "".

    Because the lesson promises that n never exceeds the length, there is nothing to clamp. The whole function is one expression.

    Step by step

    1. Slice and join in one expression. lines.slice(0, n) picks indices 0 up to but not including n, and mkString("\n") puts a newline between each two of them.

    The solution in Scala

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

    Details worth knowing:

    • A Scala Array is the JVM's array: fixed in size, with items that can be changed. It has the same collection methods as a List, including slice, take and mkString, so the code reads the same for both.
    • The array's size is lines.length. A List uses size (and length too), while an array's usual spelling is length.
    • slice returns a new array holding copies of the chosen items. Changing the new array does not touch the original.
    • Printing an array directly does not show its contents. println(arr) shows a text that starts with [Ljava.lang.String;@ followed by a number. To see the items, join them with mkString or convert with toList. Here the function returns the joined string, so the result prints properly.
    • In slice(0, n) the second argument is an end that is not included. It is not a count of items from the start, although with a start of 0 the two coincide.

    Edge cases and common mistakes

    • n = 0. slice(0, 0) is empty, so the result is "".
    • n equal to the length. With the five lines above and n = 5, every line is kept: "alpha\nbeta\ngamma\ndelta\nepsilon".
    • An empty array. Only n = 0 is allowed for it, and that gives "".
    • Off by one. slice(0, n - 1) drops the last wanted line, and slice(1, n) starts at the second line.
    • Confusing slice with take. For a prefix the two give the same lines: lines.take(n) is the same as lines.slice(0, n). The lesson uses slice to practise the "from, until" form.
    • A trailing newline. mkString places newlines between lines only, so nothing follows the last line.

    Testing

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

    CallResult
    head(g, 3)"alpha\nbeta\ngamma"
    head(g, 0)""
    head(g, 5)"alpha\nbeta\ngamma\ndelta\nepsilon"

    The next version builds on this one.

    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free