Problem overview
With a negative n, the real head -n -K prints every line except the last K. This version of head(vector<string> lines, int n) supports that. For n < 0 it returns all lines except the last |n|. For n >= 0 it behaves as in the previous version: the first n lines, capped at the input length. If |n| is at least the number of lines, nothing is left, and the result is the empty string. Lines are joined by newlines, with none after the last.
For ["a", "b", "c", "d", "e"] and n = -2, the result is "a\nb\nc": the last two lines, d and e, are dropped. With n = -1 the result is "a\nb\nc\nd", and with n = -5 or n = -9 it is "".
Approach: one end position for both signs of n
Both cases keep a prefix of the vector: the lines from position 0 up to, but not including, some position end. Only the way end is computed differs.
- For
n >= 0,endis the smaller ofnand the number of lines, as before. - For
n < 0,endis the number of lines plusn, which walks back from the end by|n|positions. With 5 lines andn = -2that gives 3, so the first three lines are kept. If|n|is as large as the list, the sum would be zero or below, so it is raised to 0 withmax.
Once end is right, the loop is the one from the earlier versions, with a newline before every line except the first. Computing end separately keeps the loop free of special cases.
Step by step
- Declare
int endwithout a value. C++ lets you declare a variable first and assign it later, and the next steps assign it in both branches. - Write the
if/elsethat separatesn < 0from every othern. - Negative branch. Set
endtomax(0, (int)lines.size() + n). The cast tointmatters: adding a negativento an unsigned size wraps around instead of subtracting. - Non-negative branch. Set
endtomin((int)lines.size(), n), the same cap as in the previous version. - Create an empty
stringnamedresult. - Loop with
ifrom 0 whilei < end.endis already right for either sign ofn. - Add the separator. When
i > 0, append"\n". - Append
lines[i]toresult. - Return
resultafter the loop.
The solution in C++
class Solution {
public:
string head(vector<string> lines, int n) {
int end;
if (n < 0) {
end = max(0, (int)lines.size() + n);
} else {
end = min((int)lines.size(), n);
}
string result;
for (int i = 0; i < end; i++) {
if (i > 0) result += "\n";
result += lines[i];
}
return result;
}
};
The C++ details worth a closer look:
- Unsigned arithmetic wraps. With 5 lines and
n = -9, the expressionlines.size() + nwithout a cast convertsnto an unsigned number first, and the result is 18446744073709551612, a huge value. With the cast,(int)lines.size() + nis -4, andmax(0, -4)brings it back to 0. - The cast also keeps
maxcompiling.max(0, lines.size() + n)mixes anintand an unsigned type, and the compiler reports that no matchingmaxexists. Casting makes both argumentsint. - Same rule for
min.minandmaxneed two arguments of one type, which is why both branches cast the size. - Declaring before assigning.
int end;has no value until one of the branches runs. Both branches assign it, so it is always set before the loop reads it. A branch that forgot to assign it would leave the loop reading an unspecified value. - The same pitfall elsewhere. On an empty vector,
lines.size() - 1is 18446744073709551615 while(int)lines.size() - 1is -1. Converting the size tointbefore doing arithmetic with signed values is the safe habit.
Complexity
Time: O(m + k) where m is the number of kept lines and k their total length. Computing end is constant time and the loop runs end times. The vector is passed by value, so the call also copies the input.
Space: O(k) for the result, plus the copy of the input.
Edge cases and common mistakes
|n|equals the number of lines.["a", "b", "c", "d", "e"]withn = -5gives"":endis exactly 0.|n|larger than the number of lines. Withn = -9the sum is -4, andmaxraises it to 0. The result is""and not an error.n = -1. Only the last line is dropped:"a\nb\nc\nd".n = 0. It takes the non-negative branch,endis 0, and the result is"". Zero keeps no lines, which is not the same as "drop zero lines".- Large positive
n. Withn = 9and 5 lines,mincapsendat 5, and every line is kept. - Empty vector. The result is
""for anyn: forn = -3the sum is -3 andmaxmakes it 0. - Skipping the
max. A negativeendwould make the loop condition false immediately, so the result would still be empty. But in the middle of other code, such anendwould be a trap, which is why the lesson clamps it.
Testing
Each result is the function's output, with newlines written as \n. The input is ["a", "b", "c", "d", "e"] unless stated:
n = -2gives"a\nb\nc".n = -1gives"a\nb\nc\nd".n = -5gives"".n = -9gives"".n = 0gives"".n = 3gives"a\nb\nc".n = 9gives"a\nb\nc\nd\ne".- An empty vector with
n = -3gives"".
