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,endis the smaller ofnand the size, as in the previous version; - for
n < 0, dropping|n|lines from the end means stopping atsize + n(adding a negative number subtracts it). With 5 lines andn = -2that 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
- Declare
endwithout a value.int end;is legal, as long as every path assigns it before it is read. - Split on the sign. Write an
if (n < 0)with anelsefor every othern. - Negative case. Set
endtoMath.max(0, lines.size() + n): all lines except the last|n|, but never below 0. - Non-negative case. Set
endtoMath.min(n, lines.size()), the cap from the previous version. - Cut and join. After the
if/else, returnString.join("\n", lines.subList(0, end)). Both branches have assignedend, 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 assignend, 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.mincaps from above,Math.maxfrom 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 = -9on 5 lines givessubList(0, -4), which throws anIllegalArgumentException.- The sum doesn't overflow.
lines.size() + nadds a non-negative size to a negativen, so the result is always in theintrange, even forInteger.MIN_VALUE, which gives an empty string. - Zero takes the second branch.
n = 0isn't negative, soendis 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, bothn = -5andn = -9give"". ForgettingMath.maxmakes the second one throw.- Treating negative
nas its absolute value.n = -2doesn't mean "the first 2 lines". It means "everything but the last 2". - Dropping one line too many or too few.
n = -1on 5 lines keeps four:"a\nb\nc\nd". - Empty input. An empty list with
n = -1gives"", becauseMath.maxlifts the negative sum to 0. - Large positive
n.n = 9on 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 = -2gives"a\nb\nc".n = -1gives"a\nb\nc\nd".n = -5andn = -9both give"".n = 0gives"".n = 3gives"a\nb\nc".n = 9gives"a\nb\nc\nd\ne".
