Problem overview
The real cat accepts many files and prints them one after another. In this version, the function concatCat takes a vector<vector<string>> named allLines. Each inner vector is one "file", a list of lines. The function returns all lines, in order, as one string joined with newlines and with none after the last line.
For [["hello", "world"], ["foo", "bar", "baz"]] the result is "hello\nworld\nfoo\nbar\nbaz". A file can be empty and contributes no lines, so [["a"], [], ["b"]] gives "a\nb". With no files at all, or only empty ones, the result is "".
Approach: flatten with two loops and a flag
The task is to flatten a vector of vectors into a single sequence of lines and join it. Two nested loops do the flattening: the outer one visits each file, and the inner one visits each line of that file.
The separator rule needs more care than in the earlier versions. Before, "add a newline when i > 0" worked because the first line was always at position 0. Here the first line might be in the second or third file, if the files before it are empty, so no loop counter reliably identifies it. For [[], ["a"]], the first line sits at i = 1, and a rule based on i would put a newline in front of a.
The fix is a bool flag, first, that starts as true and is set to false as soon as one line has been written. It answers the question the separator rule really asks: has anything been written yet?
Step by step
- Create an empty
stringnamedresult. All lines go into it. - Create
bool first = true. It remembers that no line has been written yet. - Loop over the files with
ifrom 0 whilei < allLines.size(). HereallLines[i]is one file, avector<string>. - Loop over the lines of that file with
jfrom 0 whilej < allLines[i].size(). For an empty file, this loop runs zero times. - Add the separator. In the inner loop, when
firstis false, append"\n". The very first line of everything gets no newline in front of it. - Append the line
allLines[i][j], which is linejof filei. - Set
firsttofalseas the last statement of the inner loop. From now on, every line gets a newline in front of it. - Return
resultafter both loops.
The solution in C++
class Solution {
public:
string concatCat(vector<vector<string>> allLines) {
string result;
bool first = true;
for (int i = 0; i < allLines.size(); i++) {
for (int j = 0; j < allLines[i].size(); j++) {
if (!first) result += "\n";
result += allLines[i][j];
first = false;
}
}
return result;
}
};
The C++ details worth a closer look:
- Vectors of vectors.
allLines[i]is avector<string>andallLines[i][j]is astring. The two index operators chain from left to right. Each inner vector can have its own length, soallLines[i].size()is recalculated for each file. >>in templates. The closing>>invector<vector<string>>is parsed correctly since C++11. Older compilers needed a space between the two brackets.!first. The!operator flips abool, soif (!first)reads "if this is not the first line".- The flag changes inside the inner loop. It is set to false after the first line is appended, wherever that line is. The flag lives outside both loops so that it keeps its value when the outer loop moves on to the next file.
- Copy by value. The parameter is a copy of all the lines. A
const vector<vector<string>>&would avoid the copy, but the lesson's signature takes the plain value.
Complexity
Let F be the number of files and L the total number of characters in all lines.
Time: O(F + L). The outer loop runs F times, even for empty files. The inner loops together visit every line once, and appending a line costs time proportional to its length.
Space: O(L). The result holds every character of every line, plus one newline per gap.
Edge cases and common mistakes
- No files.
[]gives"", because neither loop runs. - Only empty files.
[[], []]also gives"". - An empty file first.
[[], ["a"]]gives"a"with no leading newline. This is the case that breaks a rule based on the loop counters. - An empty file in the middle.
[["a"], [], ["b"]]gives"a\nb": the empty file adds neither a line nor a newline. - Empty strings are lines.
[[""], [""]]gives"\n": two blank lines, separated by one newline. A file that holds an empty string is different from an empty file. - Setting
first = falsein the wrong place. If it is set after the loops, or before the line is appended, the separators come out wrong. - Declaring
firstinside the outer loop. It would reset totruefor every file, and the files would be glued together with no newline between them.
Testing
Each result is the function's output, with newlines written as \n:
[["hello", "world"], ["foo", "bar", "baz"]]gives"hello\nworld\nfoo\nbar\nbaz".[["a"], [], ["b"]]gives"a\nb".[[], ["a"]]gives"a".[[""], [""]]gives"\n".[[], []]gives"".[]gives"".
