Start learning free

LESSON 606 OF 671 · PROJECTS: COMMAND-LINE TOOLS

head v4 in Java: Negative n Drops the Tail

Practice Read the full explanation

Same signature as v2/v3, but now n may be negative. Real head -n -K prints all lines except the last K. So when n < 0 return all lines except the last |n|; when n ≥ 0 behave exactly like v3 (return the first n, capped at the input length). If |n| is at least the number of lines, nothing is left, so return the empty string.

Function signature:

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

Example (negative n):

Input: lines = ["a", "b", "c", "d", "e"], n = -2

Output: "a\nb\nc"

When printed:
a
b
c

Java doesn't auto-handle negative indices. Branch on the sign of n: when n < 0, the end index is lines.size() + n; otherwise it's min(n, lines.size()). Don't forget Math.max(0, ...) for the negative branch in case |n| exceeds the list length.

int end;
if (n < 0) {
    end = Math.max(0, lines.size() + n);
} else {
    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;
        if (n < 0) {
            end = Math.max(0, lines.size() + n);
        } else {
            end = Math.min(n, lines.size());
        }
        return String.join("\n", lines.subList(0, end));
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    JAVA · PROJECTS: COMMAND-LINE TOOLS

    Head V4 in Java, explained

    Problem overview

    The fourth version lets n be negative in head(List<String> lines, int n). Real head -n -K prints every line except the last K. So for n < 0 the method returns all lines except the last |n|, and for n >= 0 it behaves as before: the first n lines, capped at the number of lines. If nothing is left, the result is the empty string.

    For ["a", "b", "c", "d", "e"] and n = -2, the last two lines are dropped, and the result is "a\nb\nc".

    Approach: one end index, two ways to compute it

    Both cases can be written as "keep the lines from index 0 up to end". Only the way to find end differs:

    • for n >= 0, end is the smaller of n and the size, as in the previous version;
    • for n < 0, dropping |n| lines from the end means stopping at size + n (adding a negative number subtracts it). With 5 lines and n = -2 that is 3.

    A very negative n would push size + n below zero, and a sublist can't end before it starts. So that value is raised to 0 with Math.max, which gives an empty result. After the if/else, one shared line cuts and joins.

    Step by step

    1. Declare end without a value. int end; is legal, as long as every path assigns it before it is read.
    2. Split on the sign. Write an if (n < 0) with an else for every other n.
    3. Negative case. Set end to Math.max(0, lines.size() + n): all lines except the last |n|, but never below 0.
    4. Non-negative case. Set end to Math.min(n, lines.size()), the cap from the previous version.
    5. Cut and join. After the if/else, return String.join("\n", lines.subList(0, end)). Both branches have assigned end, so this line works for either sign.

    The solution in Java

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

    The Java details worth a closer look:

    • Definite assignment. The compiler follows every path through the if/else. Because both branches assign end, it can be used afterwards. If one branch forgot, the code would not compile, with an error saying the variable might not have been initialized.
    • Math.min caps from above, Math.max from below. Math.min(n, size) keeps the end from going past the list. Math.max(0, ...) keeps it from going below 0. Without that floor, n = -9 on 5 lines gives subList(0, -4), which throws an IllegalArgumentException.
    • The sum doesn't overflow. lines.size() + n adds a non-negative size to a negative n, so the result is always in the int range, even for Integer.MIN_VALUE, which gives an empty string.
    • Zero takes the second branch. n = 0 isn't negative, so end is 0 and the result is "".

    Complexity

    Time: O(k + C), where k is the number of lines kept and C is their total number of characters. The branch and the sublist take constant time, and the join copies the kept lines.

    Space: O(C) for the returned string.

    Edge cases and common mistakes

    • |n| equal to or larger than the size. On 5 lines, both n = -5 and n = -9 give "". Forgetting Math.max makes the second one throw.
    • Treating negative n as its absolute value. n = -2 doesn't mean "the first 2 lines". It means "everything but the last 2".
    • Dropping one line too many or too few. n = -1 on 5 lines keeps four: "a\nb\nc\nd".
    • Empty input. An empty list with n = -1 gives "", because Math.max lifts the negative sum to 0.
    • Large positive n. n = 9 on 5 lines returns all five, as in the previous version.

    Testing

    The results below come from running the solution on ["a", "b", "c", "d", "e"]:

    • n = -2 gives "a\nb\nc".
    • n = -1 gives "a\nb\nc\nd".
    • n = -5 and n = -9 both give "".
    • n = 0 gives "".
    • n = 3 gives "a\nb\nc".
    • n = 9 gives "a\nb\nc\nd\ne".
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free