Problem overview
The signature stays head(vector<string> lines, int n), but n may now be larger than the number of lines. In that case the function returns all the lines: no crash and no padding. As before, the lines are joined by newline characters with none after the last. n is never negative here. When n is 0, or when there are no lines, the result is the empty string.
For ["alpha", "beta", "gamma"] and n = 10, the result is "alpha\nbeta\ngamma", which is the same as for n = 3. For an empty vector and n = 5 the result is "".
Approach: clamp n before the loop
The previous version looped up to n and relied on n never exceeding the number of lines. With a big n, the loop would read positions that don't exist, which is undefined behaviour in C++.
The fix is to compute how many lines can really be kept: the smaller of n and the number of lines. That number, end, bounds the loop instead of n. The rest of the function is unchanged. It is the same loop with a newline before every line except the first.
This is also the same clamp that the first version used with the fixed number 10. Here the limit is the parameter n instead.
Step by step
- Create
int endas the smaller of the number of lines andn:min((int)lines.size(), n). A largencan no longer take the loop past the vector. - Create an empty
stringnamedresult. - Loop with
ifrom 0 whilei < end. The bound isend, notn, becausenmay be bigger than the vector. - Add the separator. When
i > 0, append"\n". - Append
lines[i]toresult. - Return
resultafter the loop. It holds every kept line.
The solution in C++
class Solution {
public:
string head(vector<string> lines, int n) {
int 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:
- The cast is required.
mintakes two arguments of the same type.lines.size()is unsigned andnis anint, somin(lines.size(), n)fails to compile.(int)lines.size()makes bothint. - The cast is safe here. A vector of lines for this lesson is far smaller than the largest
int, so the conversion doesn't lose anything. - Why not compare
nwith the size directly? Mixingintand unsigned in a comparison converts theintto unsigned. A negative number would turn into a huge value. This lesson never passes a negativen, but converting the size tointinstead is the habit that keeps negative values meaningful. - Clamping instead of branching. Without
min, you would write aniffor the casen > lines.size(). One expression handles both cases and leaves the loop untouched.
Complexity
Time: O(m + k) where m is the number of kept lines and k their total length. The loop runs end times and each pass appends one line. The vector is passed by value, so the call also copies the whole input.
Space: O(k) for the result, plus the copy of the input.
Edge cases and common mistakes
nlarger than the size.["alpha", "beta", "gamma"]withn = 10returns all three lines, not extra empty ones.nequal to the size. The same result, because the minimum of two equal numbers is that number.- Empty vector.
endis 0 for everyn, so[]withn = 5gives"". n = 0.endis 0 and the result is"".- Looping to
n. This is the trap of the previous version: withn = 10and 3 lines, the positions 3 to 9 don't exist, and reading them is undefined behaviour. - Padding. Nothing is added when
nis bigger than the input. The output never has more lines than the input. - Negative
n. This version is written forn >= 0. With a negativen,mingivesenda negative value and the loop does nothing, so the result is"".
Testing
Each result is the function's output, with newlines written as \n:
["alpha", "beta", "gamma"]withn = 10gives"alpha\nbeta\ngamma".["alpha", "beta", "gamma"]withn = 3gives"alpha\nbeta\ngamma".[]withn = 5gives"".["a", "b"]withn = 0gives"".["a", "b"]withn = -1gives"".
