Start learning free

LESSON 609 OF 671 · PROJECTS: COMMAND-LINE TOOLS

head v2 in Java: First n Lines with subList(0, n)

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.size(). If n is 0 the result is the empty string.

Function signature:

public String head(List<String> lines, int n)

Example:

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

Output: "alpha\nbeta\ngamma"

When printed:
alpha
beta
gamma

Use List.subList(0, n) for the first n elements, then String.join("\n", ...). Since the problem guarantees n ≤ lines.size(), no min needed.

Combine the two calls into one:
return String.join("\n", lines.subList(0, n));


The full solution:
class Solution {
    public String head(List<String> lines, int n) {
        return String.join("\n", lines.subList(0, n));
    }
}

STEP 1 OF 1
    Ctrl + Enter to check

    JAVA · PROJECTS: COMMAND-LINE TOOLS

    Head V2 in Java, explained

    Problem overview

    The second version of the head tool takes the number of lines as a parameter: head(List<String> lines, int n). It returns the first n lines joined by \n. In this version n is promised to be between 0 and lines.size(), so the method needs no checks. When n is 0, the result is the empty string.

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

    Approach: replace the constant with n

    The previous version cut a fixed 10 lines from the list. Now the caller decides how many, so the end index of the cut is simply n. Because n never goes past the size of the list, the cut is always valid, and the whole method is one statement: take lines.subList(0, n) and join it with "\n".

    A loop that appends the first n lines one by one would also work, but it would need the separator logic again: a newline between lines and none at the end. subList and String.join already handle both, so the method states what it wants (the first n lines, joined) instead of how to build it.

    Step by step

    1. Cut and join. Pass lines.subList(0, n) to String.join("\n", ...) and return the result. The sublist holds positions 0 to n - 1, which are the first n lines.

    Nothing else is needed, because the lesson's rule keeps n inside the valid range.

    The solution in Java

    class Solution {
        public String head(List<String> lines, int n) {
            return String.join("\n", lines.subList(0, n));
        }
    }
    

    The Java details worth a closer look:

    • The range is checked when subList is called. A list of 5 lines with n = 6 throws an IndexOutOfBoundsException (its message is toIndex = 6), and a negative n such as -1 throws an IllegalArgumentException. Neither case occurs here, because of the promise about n. The following versions deal with both.
    • Zero is valid. subList(0, 0) is an empty list, and String.join turns it into "". This also covers an empty input list with n = 0.
    • Method parameters. The method has the same name as the one in version 1 but takes one more parameter, int n. In Java, a method's name plus its parameter types identify it.
    • n equal to the size. subList(0, lines.size()) is allowed: the end index is exclusive, so it may equal the size. All the lines are returned.

    Take n = 3 on the example. The sublist is [alpha, beta, gamma], the list of positions 0, 1 and 2. Joining it with a newline gives alpha, a newline, beta, a newline and gamma, with nothing after the last word. delta and epsilon at positions 3 and 4 are never read.

    Complexity

    Time: O(n + C) in the worst case, where C is the number of characters in the kept lines: the sublist is a constant-time view, and the join copies the n lines kept.

    Space: O(C) for the returned string.

    Edge cases and common mistakes

    • n = 0. The result is "", with no exception.
    • n equal to the number of lines. All five lines of the example come back for n = 5.
    • Off-by-one on the end index. subList(0, n - 1) returns one line too few, and subList(0, n + 1) one too many, or an exception when n equals the size.
    • Using the lines' count instead of n. Passing lines.size() as the end ignores the parameter and returns every line.

    Testing

    The results below come from running the solution on ["alpha", "beta", "gamma", "delta", "epsilon"]:

    • n = 3 gives "alpha\nbeta\ngamma".
    • n = 0 gives "".
    • n = 5 gives "alpha\nbeta\ngamma\ndelta\nepsilon".

    An empty list with n = 0 also gives "".

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