Start learning free

LESSON 605 OF 671 · PROJECTS: COMMAND-LINE TOOLS

head v3 in Java: 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.size() 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:

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

Example:

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

Output: "alpha\nbeta\ngamma"

When printed:
alpha
beta
gamma

List.subList(0, n) with n > lines.size() throws. So clamp n with Math.min(n, lines.size()) first.

int end = Math.min(n, lines.size());
return String.join("\n", lines.subList(0, end));


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

STEP 1 OF 2
    Ctrl + Enter to check

    JAVA · PROJECTS: COMMAND-LINE TOOLS

    Head V3 in Java, explained

    Problem overview

    The third version keeps the signature head(List<String> lines, int n), but now n may be larger than the number of lines. When it is, the method returns all the lines: it doesn't crash and doesn't pad the result. In this version n is still at least 0. When n is 0, or the list is empty, the result is the empty string.

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

    Approach: never cut past the end

    The single statement of the previous version, lines.subList(0, n), breaks as soon as n exceeds the size. The fix is to cut at the smaller of n and the number of lines. With 5 lines and n = 8 the cut ends at 5, and with n = 3 it ends at 3. The rest is unchanged: take the sublist and join it with "\n".

    Capping is a standard way to make an operation safe for any input in a range: compute the limit first, then use it.

    The same reasoning appears in many places: before using a number as an index or a length, make sure it can't go outside what the data allows. Here the data is the list, and the limit is its size. Notice that n keeps its meaning (how many lines the caller wants), while end is what the code can actually deliver. Giving the second value its own name keeps the two ideas apart.

    Step by step

    1. Compute the end index. Declare int end = Math.min(n, lines.size()). It is the number of lines actually returned, and never more than the list holds.
    2. Cut and join. Join lines.subList(0, end) with "\n" and return it, as in version 1.

    The solution in Java

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

    The Java details worth a closer look:

    • Why a cap is needed. subList throws an IndexOutOfBoundsException when the end index is larger than the list's size. Using end keeps the call inside the valid range for every n from 0 up.
    • Large values are safe. Even Integer.MAX_VALUE as n works: the minimum is the list's size, and all the lines come back.
    • Empty lists. With no lines, end is 0 for any n, and the result is "".
    • Negative n is still not handled. Math.min(-1, 3) is -1, and subList(0, -1) throws an IllegalArgumentException. The lesson promises n >= 0, and the next version deals with negative values.
    • The input is not modified. subList is a view and join builds a new string, so lines is the same afterwards.

    Complexity

    Time: O(k + C), where k is the number of lines returned and C is their total number of characters. Math.min and subList take constant time, and the join copies the returned lines.

    Space: O(C) for the returned string.

    Edge cases and common mistakes

    • n larger than the size. Forgetting the cap throws an exception instead of returning every line.
    • Padding. The result never holds more lines than the input, so n = 10 on 3 lines gives 3 lines, not 10.
    • Math.max instead of Math.min. That would pick the larger number, which is the opposite of a cap, and it would throw for short lists.
    • n = 0 and empty lists. Both give "".

    Testing

    The results below come from running the solution:

    • ["alpha", "beta", "gamma"] with n = 10 gives "alpha\nbeta\ngamma".
    • ["alpha", "beta", "gamma", "delta"] with n = 3 gives "alpha\nbeta\ngamma".
    • ["alpha", "beta", "gamma"] with n = 0 gives "".
    • An empty list with n = 4 gives "".
    • ["alpha", "beta", "gamma"] with n = Integer.MAX_VALUE gives "alpha\nbeta\ngamma".
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free