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
- 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. - 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.
subListthrows anIndexOutOfBoundsExceptionwhen the end index is larger than the list's size. Usingendkeeps the call inside the valid range for everynfrom 0 up. - Large values are safe. Even
Integer.MAX_VALUEasnworks: the minimum is the list's size, and all the lines come back. - Empty lists. With no lines,
endis 0 for anyn, and the result is"". - Negative
nis still not handled.Math.min(-1, 3)is-1, andsubList(0, -1)throws anIllegalArgumentException. The lesson promisesn >= 0, and the next version deals with negative values. - The input is not modified.
subListis a view andjoinbuilds a new string, solinesis 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
nlarger 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 = 10on 3 lines gives 3 lines, not 10. Math.maxinstead ofMath.min. That would pick the larger number, which is the opposite of a cap, and it would throw for short lists.n = 0and empty lists. Both give"".
Testing
The results below come from running the solution:
["alpha", "beta", "gamma"]withn = 10gives"alpha\nbeta\ngamma".["alpha", "beta", "gamma", "delta"]withn = 3gives"alpha\nbeta\ngamma".["alpha", "beta", "gamma"]withn = 0gives"".- An empty list with
n = 4gives"". ["alpha", "beta", "gamma"]withn = Integer.MAX_VALUEgives"alpha\nbeta\ngamma".
