Problem overview
The real cat command accepts several files and prints them one after another. This version models that. The method ConcatCat receives a List<List<string>>: each inner list is one "file", made of lines. It returns all the lines, in order, joined by newlines.
For [["hello", "world"], ["foo", "bar", "baz"]] the result is "hello\nworld\nfoo\nbar\nbaz", which prints as five lines. A file can be empty and adds no lines. If there are no files at all, the result is an empty string.
Approach
Joining a list of strings was already solved in the first version of the tool, with string.Join. The only new problem here is that the lines come in several lists. So the work splits in two steps: first flatten the nested lists into one list of lines, then join that list.
Flattening needs two loops, one inside the other. The outer loop visits the files in order. The inner loop visits the lines of the current file in order. Adding each line to a new list flat keeps the original order: all of file 1, then all of file 2, and so on.
A separator-based join is also the answer to the "between, not after" rule. Joining the flat list puts a newline between neighbouring lines and none after the last. It doesn't matter which file a line came from. The last line of one file and the first line of the next are simply neighbours. Building the joined string for every file separately and gluing the pieces would need extra care at the file boundaries.
Step by step
- Create
flat:List<string> flat = new List<string>();. It will hold every line of every file, with no lists inside it. - Loop over the files with
foreach (List<string> fileLines in allLines). Each element ofallLinesis itself a list of lines. - Loop over the lines of this file with
foreach (string line in fileLines), inside the first loop. - Add the line:
flat.Add(line). An empty file never enters the inner loop, so it adds nothing. - Return
string.Join("\n", flat)after both loops.
The solution in C#
class Solution {
public string ConcatCat(List<List<string>> allLines) {
List<string> flat = new List<string>();
foreach (List<string> fileLines in allLines) {
foreach (string line in fileLines) {
flat.Add(line);
}
}
return string.Join("\n", flat);
}
}
C# details worth knowing:
- A list of lists is a type of its own.
List<List<string>>is a list whose elements areList<string>. Each inner list can have a different length, including zero. Note the two closing angle brackets. foreachneeds no index. Here you only need each item in order, soforeachis shorter and cannot go out of range.- Loop variable names say what they hold.
fileLinesis a whole file,lineis one string. Mixing the two up is a type error the compiler catches. - Without loops. With
using System.Linq;,allLines.SelectMany(f => f)flattens a list of lists, andstring.Join("\n", allLines.SelectMany(f => f))returns the same result as the solution for[["a", "b"], ["c"]],"a\nb\nc". The explicit loops need no extrausingand show what happens. string.Joinaccepts a list directly, so there is no need to convertflatto an array.
Complexity
Time: O(total length). Each line is visited once while flattening, and string.Join copies each character once. Adding to a List takes amortised constant time.
Space: O(total length). flat holds a reference to every line (the line strings themselves are not copied), and the joined result is a new string with all the text.
Edge cases and common mistakes
- Empty files.
[["a"], [], ["b"]]gives"a\nb". The empty file contributes no line and no extra newline. - No files.
[]gives"", and so does[[], []]. - Files with only a blank line. A blank line is still a line.
[[""], [""]]gives"\n": two empty lines with a newline between them. - A single file.
[["x"]]gives"x", with no newline. - A newline between files by hand. Appending
"\n"after each file leaves a trailing newline at the end, and an empty file would still add a newline of its own. Flattening first avoids both. - Changing the order. The files and their lines must stay in the order given. Don't sort.
- A
nullfile. If one of the inner lists isnull, the innerforeachthrows aNullReferenceException. The lesson passes real lists, possibly empty ones.
Testing
[["hello", "world"], ["foo", "bar", "baz"]]gives"hello\nworld\nfoo\nbar\nbaz".[["a"], [], ["b"]]gives"a\nb".[]gives"".[[], []]gives"".[[""], [""]]gives"\n".[["x"]]gives"x".
