Problem overview
The real cat accepts several files and prints them one after another. In this version each "file" is an array of lines, so the input is an array of arrays: concatCat(_ allLines: [[String]]) -> String. The function puts all the lines in order, from the first file's first line to the last file's last line, and joins them with newlines.
For [["hello", "world"], ["foo", "bar", "baz"]] the result is "hello\nworld\nfoo\nbar\nbaz". Printed, it is five lines. A file can be empty and add no lines, and with no files at all the result is the empty string.
Approach
There are two jobs: flatten the nested arrays into a single array of lines, then join that array. The second job is the same joined(separator:) call as in the first version of cat. The first is a loop inside a loop: the outer loop visits each file and the inner loop visits each line of that file, appending it to one flat array.
Doing the join once at the end, rather than adding newlines while looping, keeps the newline rule simple. A newline appears between two lines and never at the ends, and joined guarantees that however many files are empty. A file with no lines never enters the inner loop, so it contributes nothing, not even an extra separator.
Step by step
- Create
var flat: [String] = [], an empty array of strings. It will hold every line of every file, in order. The type annotation is needed because an empty literal gives Swift nothing to infer the element type from. - Loop over the files with
for fileLines in allLines. EachfileLinesis itself a[String]. - Loop over that file's lines with
for line in fileLines, inside the first loop. - Append the line to
flatwithflat.append(line). Because the outer loop goes through the files in order and the inner loop goes through each file's lines in order, the lines end up in the right order. - Return the joined array after both loops:
flat.joined(separator: "\n").
The solution in Swift
class Solution {
func concatCat(_ allLines: [[String]]) -> String {
var flat: [String] = []
for fileLines in allLines {
for line in fileLines {
flat.append(line)
}
}
return flat.joined(separator: "\n")
}
}
Swift details worth a closer look:
for ... inneeds no indices. The loop variable takes each element directly, so there is no index arithmetic to get wrong.- Loop variables are constants.
fileLinesandlinecan be read but not assigned to inside the loops. flatis avar.appendchanges the array, and Swift only allows that on avar. Declaring it withletwould be a compile error.- A shorter form exists.
allLines.flatMap { $0 }produces the same flat array in one expression. Writing the loops out makes the flattening visible, which is the point of this lesson.
Complexity
Every line is visited once and appended to flat, and appending to an array is constant time on average. The final join copies each character once. Time is proportional to the total size of the input. The extra space is the flat array and the result string, also proportional to the total size.
Edge cases and common mistakes
- Empty files.
[["a"], [], ["b"]]gives"a\nb". The empty file adds no line and no newline. - No files.
[]and[[], []]both give"". - Blank lines are lines. A file that holds
[""]has one line, which is blank. So[[""], [""]]gives"\n": two blank lines with a newline between them. - Joining each file separately. Joining every file on its own and then joining those strings with newlines breaks on an empty file: its empty string still gets separators around it, so
[["a"], [], ["b"]]would give"a\n\nb". Flattening first avoids that. - A trailing newline. Adding
"\n"after every line would end the result with a newline that the lesson doesn't expect.
Testing
| Input | Result (as a Swift literal) |
|---|---|
[["hello", "world"], ["foo", "bar", "baz"]] | "hello\nworld\nfoo\nbar\nbaz" |
[["a"], [], ["b"]] | "a\nb" |
[[""], [""]] | "\n" |
[] | "" |
[[], []] | "" |
