Problem overview
The Unix cat command prints text line by line. This first version of the project is a function, cat(lines: string[]): string, that takes the lines and returns one string with a newline character between each two of them. Printing that string puts one line on each row.
For ["hello", "world", "foo"] the result is "hello\nworld\nfoo". Blank lines are ordinary entries, and an empty list gives an empty string.
Approach: join, not concatenation in a loop
You could build the result by looping and adding "\n" after each line, but then the last line would end with a newline the expected output doesn't have. The key word in the task is "between": the separator goes between two lines, never after the last one.
Arrays have a method for exactly this. array.join(separator) glues the elements into one string with the separator between each pair. It adds nothing before the first element or after the last, and an array with one element comes back as that element alone.
Here is what the loop version produces for ["hello", "world", "foo"] if it adds "\n" after every line:
"hello\nworld\nfoo\n"
That has 16 characters, one more than the correct result, "hello\nworld\nfoo", which has 15. join gets it right without a special case for the last line.
Calling join() with no argument is a different trap: the default separator is a comma, so ["hello", "world", "foo"] gives "hello,world,foo". The newline has to be passed explicitly.
Step by step
- Return
lines.join("\n"). That is the whole function: the separator is the newline escape"\n", andjoinplaces it between the lines.
The solution in TypeScript
class Solution {
cat(lines: string[]): string {
return lines.join("\n");
}
}
A few details are worth knowing:
"\n"is a single character, the newline. In the result it is a real line break; it only looks like two characters in the source code.joindoes not changelines. It builds and returns a new string.- The types
string[]andstringare checked by the compiler and then erased when the code becomes JavaScript. The function itself is plain JavaScriptjoin.
To see the result as a person would, pass it to console.log. The string "hello\nworld\nfoo" is shown as three rows:
hello
world
foo
The function only builds the string; printing is left to the caller.
Complexity
Time is O(total length), since every character of every line is copied into the result once. Space is the same, for the new string.
Edge cases and common mistakes
- Empty list.
[].join("\n")is"", so no special case is needed. - One line.
["x"]gives"x", with no newline. - Blank lines. An empty string is still an entry.
["a", "", "b"]gives"a\n\nb", which prints as a blank row betweenaandb. A list holding only[""]gives"", the same as an empty list: one blank line has no characters to show. - A trailing newline. Don't add
"\n"at the end. The tests expect none.
Testing
| Input | Result |
|---|---|
["hello", "world", "foo"] | "hello\nworld\nfoo" |
["a", "", "b"] | "a\n\nb" |
["x"] | "x" |
[] | "" |
