Problem overview
The real cat takes several files and prints them one after another. This version models that with concatCat(allLines). The argument is an array of "files", and each file is itself an array of lines. The method flattens all the lines in order and joins them with newlines.
For [["hello", "world"], ["foo", "bar", "baz"]] the result is "hello\nworld\nfoo\nbar\nbaz". A file can be empty and add no lines, and with no files at all the result is an empty string.
Approach: flatten first, join once
Collecting all the lines into one flat array makes the rest trivial, because that array can be joined exactly as in the first version. The flattening takes a loop inside a loop. The outer loop visits each file, and the inner loop visits each line of that file and pushes it onto the flat array. Files are read in order and lines in order inside each file, so the order of the output follows the input.
Joining once at the end, rather than once per file, matters. Joining each file and then joining those results would also work, but an empty file would then produce an empty piece, and an extra blank row would show up between files.
To see the difference, compare the two orders on [["a"], [], ["b"]]. Flattening first and joining once gives "a\nb". Joining each file separately and then joining those results gives "a\n\nb", with a blank row where the empty file was.
Step by step
- Create an empty array named
flat. It will hold every line of every file, with no arrays inside it. - Loop over the files with
i. HereallLines[i]is one file, an array of lines. - Loop over that file's lines with
j, inside the first loop, up toallLines[i].length. - Push
allLines[i][j]ontoflat. An empty file never enters the inner loop, so it adds nothing. - Return
flat.join("\n")after both loops, so it runs once.
The solution in JavaScript
class Solution {
concatCat(allLines) {
let flat = [];
for (let i = 0; i < allLines.length; i++) {
for (let j = 0; j < allLines[i].length; j++) {
flat.push(allLines[i][j]);
}
}
return flat.join("\n");
}
}
Language details
- The two indexes are separate:
ipicks the file andjpicks the line, which is why the line isallLines[i][j]. - The inner bound is
allLines[i].length, the length of the current file, not of the whole list. - The built-in
flat()method does the same flattening in one call:[["a"], [], ["b", "c"]].flat().join("\n")gives"a\nb\nc". The lesson writes the loops out so the process is visible.
Testing
The method returns these results:
[["a"],[],["b","c"]] -> "a\nb\nc"
[[],[]] -> ""
[] -> ""
Edge cases and common mistakes
- Empty files. The empty array between
["a"]and["b", "c"]contributes nothing, and no blank row appears. - No files. The outer loop never runs,
flatstays empty, andjoinreturns"". - Mixing up the indexes. Writing
allLines[j][i]reads the wrong element or throws when a file is shorter. - Returning inside a loop. The
returnbelongs after both loops, otherwise the method stops after the first line.
