Problem overview
The first version of head always kept 10 lines. This version takes the count as a parameter: head(vector<string> lines, int n) returns the first n lines joined by newline characters, with no newline after the last. For this lesson, n is always between 0 and lines.size(), so it never asks for more lines than exist. When n is 0, the result is the empty string.
For ["alpha", "beta", "gamma", "delta", "epsilon"] and n = 3, the result is "alpha\nbeta\ngamma". With n = 0 it is "", and with n equal to the number of lines every line is kept.
Approach: let n bound the loop
The change from the previous version is small: the fixed 10 becomes the parameter n. The loop runs while i < n, so i takes the values 0 to n - 1, which are the positions of the lines to keep. The joining rule is unchanged: put a newline before every line except the first, so newlines only appear between lines.
Because the lesson promises n <= lines.size(), there is nothing to clamp, and the loop can use n directly. That promise is the whole reason this version is so short. Without it, lines[i] could ask for a position that doesn't exist. This version relies on the guarantee, and the next one builds on it.
Step by step
- Create an empty
stringnamedresult. It grows by one line per pass. - Loop with
ifrom 0 whilei < n. The counter visits exactly the positions of the firstnlines. - Add the separator. When
i > 0, append"\n". The first line has nothing before it to separate from. - Append
lines[i]toresult. - Return
resultafter the loop. Forn = 0, the loop never runs andresultis still empty.
The solution in C++
class Solution {
public:
string head(vector<string> lines, int n) {
string result;
for (int i = 0; i < n; i++) {
if (i > 0) result += "\n";
result += lines[i];
}
return result;
}
};
The C++ details worth a closer look:
- No bounds check on
[].lines[i]with a position past the end is undefined behaviour: the program may crash, print garbage or seem to work. The code is correct only becausennever exceeds the number of lines. Theatmethod,lines.at(i), checks the position and throwsstd::out_of_rangeinstead, which is easier to debug. - A signed loop counter.
iandnare bothint, soi < ncompares two signed numbers. Thesize()comparison from earlier versions is not needed here. - The condition
i > 0. It is false only on the first pass. That is the compact way to write "all but the first".
Complexity
Time: O(n + k) where k is the total length of the kept lines. The loop runs n times, and each pass appends one line, which costs time proportional to its length. Because the vector is passed by value, the call also copies every line of the input.
Space: O(k) for the result, plus the copy of the input.
Edge cases and common mistakes
n = 0. The loop is skipped and the result is"", even when there are lines.n = 1. The result is the first line alone, with no newline:["alpha", "beta"]withn = 1gives"alpha".nequal to the size. Every line is kept:["alpha", "beta"]withn = 2gives"alpha\nbeta".- Off by one. A loop condition of
i <= nreturnsn + 1lines, and reads past the end whennequals the size. - A trailing newline. The separator goes before a line, not after it, so the result never ends with
\n. - Calling it with a larger
n. This version does not handlenabove the number of lines: the loop would read positions that do not exist. The lesson excludes that case.
Testing
Each result is the function's output, with newlines written as \n:
["alpha", "beta", "gamma", "delta", "epsilon"]withn = 3gives"alpha\nbeta\ngamma".["alpha", "beta"]withn = 0gives"".["alpha", "beta"]withn = 1gives"alpha".["alpha", "beta"]withn = 2gives"alpha\nbeta".
