Problem overview
The Unix cat command prints text line by line. This first version of the tool is a function, cat, that takes a vector<string> of lines and returns one string in which the lines are separated by newline characters. Printing that string shows one line per row.
For ["hello", "world", "foo"] the result is "hello\nworld\nfoo". The newlines sit between the lines: there is none after foo. Blank lines are real lines, so ["a", "", "b"] gives "a\n\nb", and an empty vector gives the empty string.
Approach: add a separator before every line except the first
C++ has no standard join function for strings, so the result is built by hand: start with an empty string and append to it. The only decision is where the separators go. If every line were followed by "\n", the result would end with an extra newline. If every line were preceded by one, it would start with one.
The fix is to put a newline before each line except the first. Counting lines by position makes that easy: when the position i is above 0, something has already been written, so a separator is needed first.
Later versions of the tool build on this function, so the pattern "separator before every item but the first" is worth keeping in mind.
Step by step
- Create an empty
stringnamedresult. Every line is appended to it, and it is what the function returns. - Loop over the positions with an
intcounterifrom 0 whilei < lines.size(). The position is needed, not only the line, because the first line is treated differently. - Add the separator. A one-line
if (i > 0)appends"\n". On the first pass nothing is appended. - Append the line:
result += lines[i]. An empty line appends nothing, but its separator was already added, which is how blank lines survive. - Return
resultafter the loop. It must sit outside the braces, or the function would return after the first line.
The solution in C++
class Solution {
public:
string cat(vector<string> lines) {
string result;
for (int i = 0; i < lines.size(); i++) {
if (i > 0) result += "\n";
result += lines[i];
}
return result;
}
};
The C++ details worth a closer look:
- Strings start empty.
string result;already holds the empty string, with no initial value needed. +=appends in place. It works with both a string literal ("\n") and anotherstring(lines[i]). In a string literal,\nis a single newline character.size()is unsigned. Comparing it with theintiis fine here and the code compiles, although some compilers warn about the mixed signs. It would become a problem if you subtracted from it:lines.size() - 1on an empty vector wraps around to a huge number instead of becoming -1.- The vector is passed by value. The function receives a copy of the lines. For this lesson that is fine. For large inputs, a
const vector<string>¶meter avoids the copy, but the lesson's signature uses the plain vector.
Complexity
Time: O(total length). The loop visits each line once, and appending a line costs time proportional to its length. Appending to a string takes amortized constant time per character, because the string grows its buffer geometrically.
Space: O(total length). The result holds every character of every line, plus one newline per gap.
Edge cases and common mistakes
- Empty vector. The loop doesn't run, and the function returns
"". - One line.
["solo"]gives"solo", with no newline, becauseiis never above 0. - A vector holding only an empty string.
[""]gives"": one line, and it is empty. Two empty strings give"\n", and three give"\n\n". - A trailing newline. Adding
"\n"after every line would turn"hello\nworld\nfoo"into"hello\nworld\nfoo\n", which does not match the expected output. - Returning inside the loop. A
return result;placed before the loop's closing brace stops after the first line.
Testing
Each result below is the function's output with newlines written as \n:
["hello", "world", "foo"]gives"hello\nworld\nfoo".["a", "", "b"]gives"a\n\nb".["solo"]gives"solo".["", "", ""]gives"\n\n".[]gives"".
