Start learning free

LESSON 4 OF 70 · PROJECTS: COMMAND-LINE TOOLS

cat v4 in Kotlin: Join Several Files with Nested Loops

Practice Read the full explanation

The real cat command can take many files as arguments and prints them one after another. Build that behavior. Given a list of "files" where each file is itself a list of lines, flatten all lines in order and join them with newlines.

A file can be empty (it adds no lines), and the list can hold no files at all; the result is then an empty string.

Function signature:

fun concatCat(allLines: List<List<String>>): String

Example:

Input: allLines = [["hello", "world"], ["foo", "bar", "baz"]]

Output: "hello\nworld\nfoo\nbar\nbaz"

When printed:
hello
world
foo
bar
baz

Build a flat MutableList<String> with a nested loop, preserving order. Then return flat.joinToString("\n").

val flat = mutableListOf<String>()
for (fileLines in allLines) {
    for (line in fileLines) {
        flat.add(line)
    }
}
return flat.joinToString("\n")


The full solution:
class Solution {
    fun concatCat(allLines: List<List<String>>): String {
        val flat = mutableListOf<String>()
        for (fileLines in allLines) {
            for (line in fileLines) {
                flat.add(line)
            }
        }
        return flat.joinToString("\n")
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    KOTLIN · PROJECTS: COMMAND-LINE TOOLS

    Cat V4 in Kotlin, explained

    Problem overview

    The real cat takes several files and prints them one after another. Here a "file" is a list of lines, so the input is a list of lists: fun concatCat(allLines: List<List<String>>): String. You flatten every line of every file, in order, and join them with newlines.

    A file can be empty and adds no lines. If there are no files at all, the result is an empty string. For [["hello", "world"], ["foo", "bar", "baz"]] the result is "hello\nworld\nfoo\nbar\nbaz". The lines of the second file continue straight after the last line of the first.

    Approach

    Joining with newlines is easy once you have a single flat list of lines, and the previous versions already use joinToString("\n") for it. So the work is the flattening: for each file, for each line in that file, add the line to one result list. Two nested loops do it, and they keep the order: files in the order given, lines in the order of their file.

    The join happens once at the end, over all lines. That matters, as the common mistakes below show.

    Step by step

    1. Create val flat = mutableListOf<String>(). It is the one flat list that will hold every line. The type argument is needed because nothing in the call tells Kotlin what the list holds.
    2. Loop over the files: for (fileLines in allLines). Each fileLines is a List<String>.
    3. Loop over that file's lines: for (line in fileLines), inside the first loop.
    4. Add the line: flat.add(line). An empty file never enters the inner loop, so it adds nothing and needs no special case.
    5. Return flat.joinToString("\n") after both loops.

    The solution in Kotlin

    class Solution {
        fun concatCat(allLines: List<List<String>>): String {
            val flat = mutableListOf<String>()
            for (fileLines in allLines) {
                for (line in fileLines) {
                    flat.add(line)
                }
            }
            return flat.joinToString("\n")
        }
    }
    

    Calling it on a few inputs (newlines written as \n):

    allLinesresult
    [["hello", "world"], ["foo", "bar", "baz"]]"hello\nworld\nfoo\nbar\nbaz"
    [["a"], [], ["b"]]"a\nb"
    [["a"], ["b"]]"a\nb"
    [["a", ""], ["", "b"]]"a\n\n\nb"
    [[], []]""
    []""

    The fourth row shows that blank lines survive: the lines are a, an empty line, another empty line and b, so there are three newlines.

    Kotlin details worth knowing

    • Read-only parameter, mutable local. allLines is a read-only List<List<String>>; you only read it. The list you build, flat, is a MutableList, which has add.
    • val doesn't make the list frozen. val flat means you can't point flat at a different list, but you can still add to the one it holds.
    • There is a built-in for flattening. allLines.flatten() returns a single List<String> of all the lines in order, so allLines.flatten().joinToString("\n") gives the same result on the lesson's examples. The lesson uses explicit loops so you see how the flattening works.

    Complexity

    Every line is visited once and added once, so the time is proportional to the total number of lines, plus the size of the text when joining. The extra space is the flat list and the joined string, both proportional to the input.

    Edge cases and common mistakes

    • Joining each file first. If you turn every file into its own string and then join those strings with "\n", an empty file contributes an empty string between two separators. [["a"], [], ["b"]] would give "a\n\nb", with a blank line that isn't in the input.
    • Adding a newline after every file. The result then ends with a newline, or has one extra between files, and no longer matches the expected text.
    • Filtering out blank lines. An empty string in a file is a real blank line and must stay.
    • Mixing up the loop variables. The outer loop gives a whole file, a list; the inner loop gives one line, a string. Calling flat.add(fileLines) doesn't compile, because flat holds strings.
    • Empty input. No files, or only empty files, means nothing is added and joinToString on an empty list gives "".
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free