Problem overview
The Unix head command prints the beginning of its input, ten lines by default. The function head takes a vector<string> of lines and returns the first 10 of them as one string, joined by newline characters with none after the last. With fewer than 10 lines it returns all of them, and with no lines it returns the empty string.
For the 13 lines "a" to "m", the result is "a\nb\nc\nd\ne\nf\ng\nh\ni\nj": the letters k, l and m are dropped. With exactly 10 lines the result is the same string, and with the three lines "a", "b" and "c" it is "a\nb\nc".
Approach: decide how many lines to keep, then join them
The work splits into two small parts. First, find how many lines to keep: 10, or fewer if the input is shorter. Second, join exactly that many lines with newlines between them, using the same loop as the cat tool: a separator before every line except the first.
The count is where the care goes. A loop that always runs to 10 would read past the end of a shorter vector, and reading an element that doesn't exist is undefined behaviour in C++: it may crash or silently return garbage. So the loop bound is the smaller of 10 and the number of lines, which min computes.
Step by step
- Create
int endas the smaller of the number of lines and 10:min((int)lines.size(), 10). It is the number of lines to keep. - Create an empty
stringnamedresult. It grows by one line per pass. - Loop over the kept positions with
ifrom 0 whilei < end, soigoes through 0 up toend - 1. - Add the separator. When
i > 0, append"\n". That puts one newline between each pair of lines and none after the last. - Append
lines[i]toresult. - Return
resultafter the loop. For an empty input the loop never ran, so it is still the empty string.
The solution in C++
class Solution {
public:
string head(vector<string> lines) {
int end = min((int)lines.size(), 10);
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:
- Why the cast.
lines.size()returns an unsigned type, and10is anint.minneeds both arguments to have the same type, somin(lines.size(), 10)does not compile. Casting the size with(int)makes both argumentsint. minlives in<algorithm>. It is the standard library'sstd::min. The lesson's file already has the headers and theusing namespace std;line, so the plain name works.- The variable is called
end. It is an ordinary local name here. Unrelated to it, containers have a member functionend(), and the two don't clash. - Vectors don't check indexes.
lines[i]does no bounds check, which is why the loop bound has to be right. Computingendfirst is what keeps everyia valid position.
Complexity
Time: O(k) where k is the total length of the kept lines, which are at most 10. The loop runs at most 10 times, and each pass appends one line. Passing the vector by value copies all of its lines first, which makes the call O(n) in the size of the whole input.
Space: O(k) for the result, plus the copy of the input that the by-value parameter makes.
Edge cases and common mistakes
- Fewer than 10 lines.
endis the vector's size, so every line is kept. - Exactly 10 lines. Nothing is dropped, and the result is all ten.
- Empty vector.
endis 0, the loop does nothing, and the result is"". - Looping to 10 unconditionally. With 3 lines this reads positions 3 to 9, which do not exist.
- A trailing newline. Appending
"\n"after every line, instead of before every line but the first, would leave an extra newline at the end. - Using
lines.size()inminwithout a cast. The compiler rejects the mixed types.
Testing
Each result is the function's output, with newlines written as \n:
- The 13 lines
"a"to"m"give"a\nb\nc\nd\ne\nf\ng\nh\ni\nj". - The first 10 of those lines give the same string.
- The first 3 of those lines give
"a\nb\nc". []gives"".
