Problem overview
This version of Head(List<string> lines, int n) accepts a negative n, like the real head -n -K, which prints all lines except the last K. So for n < 0 the method returns all lines except the last |n|. For n >= 0 it behaves as in the previous version: the first n lines, capped at the length of the input. If |n| is at least the number of lines, nothing is left and the result is "".
For ["a", "b", "c", "d", "e"] with n = -2 the result is "a\nb\nc": the last two lines are dropped.
Approach
Both cases can be described the same way: keep the first end lines, where end is a count. Only the calculation of end differs.
- For
n >= 0,endisMath.Min(n, lines.Count): the firstnlines, but never more than exist. - For
n < 0, you keep everything except the last|n|lines. Withlines.Countlines, that islines.Count - |n|, which islines.Count + nbecausenis negative. Five lines andn = -2keep5 + (-2) = 3lines.
If |n| is as large as the list or larger, lines.Count + n is zero or below. A count can't be negative, so it is lifted to 0 with Math.Max(0, ...), and the result is empty.
Once end is known, one line finishes the job for both signs: string.Join("\n", lines.GetRange(0, end)).
Step by step
- Declare
int end;without a value. C# lets you declare a variable and assign it later, as long as every path through the code assigns it before it is used. Both branches below do. - Write an
if/elsethat separatesn < 0from every othern. - In the
if: setend = Math.Max(0, lines.Count + n);.Math.Maxreturns the larger of two numbers, so a negative count becomes 0. - In the
else: setend = Math.Min(n, lines.Count);, the clamp from the previous version. - Return the joined range:
string.Join("\n", lines.GetRange(0, end)). Since both branches setend, this line works for either sign.
The solution in C#
class Solution {
public string Head(List<string> lines, int n) {
int end;
if (n < 0) {
end = Math.Max(0, lines.Count + n);
} else {
end = Math.Min(n, lines.Count);
}
return string.Join("\n", lines.GetRange(0, end));
}
}
C# details worth knowing:
- Negative indices don't exist. Some languages let you write
lines[-2]or slice with a negative bound. In C#, an index or count below 0 throws, so a negativenhas to be converted by hand into a position from the start:lines.Count + n. - Definite assignment. The compiler checks that
endhas a value on every path before thereturn. If theelsewere missing, the line usingendwould be a compile error ("use of unassigned local variable"). Math.MaxandMath.Minare mirrors.Minkeeps a count from going above the size of the list.Maxkeeps it from going below 0.- The arithmetic can't overflow in practice.
lines.Count + nadds a non-negative count and a negative number, so the sum stays inside the range ofint. It works even withn = int.MinValue, which gives"".
Complexity
Time: O(k + length of the kept lines), where k is the number of lines kept. GetRange copies k references and Join copies the kept text once.
Space: O(k + length of the kept lines). The sub-list and the result string.
Edge cases and common mistakes
|n|equal to the list size. Five lines andn = -5give5 + (-5) = 0kept lines, so"".|n|larger than the list.n = -9on five lines would give-4without theMath.Max, andGetRange(0, -4)would throw. With it the result is"".n = -1. Only the last line is dropped: for["alpha", "beta", "gamma", "delta", "epsilon"]the result is"alpha\nbeta\ngamma\ndelta".n = 0. It takes the non-negative branch and keeps 0 lines, so the result is"". It does not mean "drop zero lines".- Large positive
n.Math.Mincaps it:n = 10on five lines returns all five. - An empty list. Both
n = -3andn = 3return"". - Subtracting instead of adding. Because
nis already negative,lines.Count - nwould add|n|and ask for more lines than exist.
Testing
["a", "b", "c", "d", "e"]withn = -2gives"a\nb\nc".- The lines
"alpha","beta","gamma","delta","epsilon"withn = -1give"alpha\nbeta\ngamma\ndelta". - The same five lines with
n = -4give"alpha". - The same lines with
n = -5and withn = -9give"". - The same lines with
n = 3give"alpha\nbeta\ngamma", and withn = 10all five lines. - The same lines with
n = 0give"". - An empty list with
n = -3gives"".
