Problem overview
The Unix head command shows the beginning of a file. This first version is a method, head(lines: string[]): string, that returns the first 10 lines joined by newline characters. With fewer than 10 lines it returns all of them, and with no lines it returns an empty string.
For the 13 lines "a" to "m", the result is "a\nb\nc\nd\ne\nf\ng\nh\ni\nj". Lines k, l and m are left out.
Approach: take a slice, then join
There are two jobs: cut the array down to at most 10 items, then glue the items together with "\n" between them. The second job is join("\n"), which puts the separator between items and none after the last one.
For the first job you could loop and stop at 10 or at the end of the array, whichever comes first. The built-in slice(start, end) already does that. It returns a new array with the items from index start up to, but not including, index end. If end is past the end of the array, it stops at the end instead of failing.
That last property is why no special cases are needed. For a 13-item array, slice(0, 10) returns items 0 to 9. For a 4-item array it returns all 4, and for an empty array it returns an empty array, which join turns into an empty string.
Step by step
- Return
lines.slice(0, 10).join("\n").slice(0, 10)takes the first 10 lines or all of them if there are fewer, andjoin("\n")turns that array into one string with a newline between each two lines.
The solution in TypeScript
class Solution {
head(lines: string[]): string {
return lines.slice(0, 10).join("\n");
}
}
- The end index is exclusive.
slice(0, 10)gives indexes 0 to 9, which is 10 items, so the number in the call is the count when the start is 0. slicereturns a new array and leaveslinesalone. Pushing onto the returned array doesn't change the input.- Don't confuse it with
splice, which removes items from the original array, or withsubstring, which works on strings. - The compiler checks the types
string[]andstring, and then they are erased. The compiled JavaScript is the same two method calls.
Complexity
Copying at most 10 items is constant work, and joining them costs time proportional to the length of those lines. The cost doesn't grow with the number of lines in the input, because the slice ignores everything after the tenth.
Edge cases and common mistakes
- Fewer than 10 lines. All of them come back, with no padding and no error.
- Exactly 10 lines. All 10 come back.
- Empty list. The result is
"". - Off by one.
slice(0, 9)returns 9 lines andslice(1, 10)skips the first. The first argument is where to start, the second is where to stop. - A trailing newline. The result has none: the separator goes between lines only.
Testing
| Input | Result |
|---|---|
13 lines, "a" to "m" | "a\nb\nc\nd\ne\nf\ng\nh\ni\nj" |
["alpha", "beta"] | "alpha\nbeta" |
[] | "" |
