Problem overview
This version of the wc project builds the word count, the job of wc -w. The method countWords(lines: string[]): number receives an array of lines and returns the total number of words in all of them. A word is a run of non-whitespace characters, and words are separated by one or more spaces or tabs.
For ["hello world", "foo bar baz", ""] the answer is 5: two words, three words and none for the empty line. Leading and trailing whitespace is ignored, a line with only whitespace has no words, and an empty array gives 0.
Approach: split each line, then add up the pieces
The plan has two layers. For one line, cut it into words and count them. Over the whole array, add those counts into a running total. A for...of loop handles the outer layer, and a chain of three string and array methods handles the inner one.
The inner layer has a trap. Splitting a string on a pattern does not give an empty array for an empty string. It gives one empty piece:
"".split(/\s+/); // [""] (one piece, not zero)
" ".trim().split(/\s+/); // [""]
" a b".split(/\s+/); // ["", "a", "b"] (leading whitespace gives an empty first piece)
Counting the pieces without cleaning them up would make every blank line count as one word. Trimming the line first removes the leading and trailing whitespace pieces, and filtering removes the one empty piece that blank lines still produce.
Step by step
- Create the total. Declare
totalwithletand start it at 0. It changes as lines are read, so it can't be aconst. - Visit every line. A
for (const line of lines)loop gives each string in turn. Everything that follows goes inside its braces. - Cut the line into words. Call
trim()to strip whitespace at both ends,split(/\s+/)to cut at every run of whitespace, andfilter(x => x)to keep only the pieces that are not empty text. An empty string is falsy, so the filter drops it and keeps every real word. The result is stored intokens, typedstring[]. - Add the line's words.
tokens.lengthis the number of words on this line, so add it tototal. - Return the total after the loop, once every line has been counted.
The solution in TypeScript
class Solution {
countWords(lines: string[]): number {
let total = 0;
for (const line of lines) {
const tokens: string[] = line.trim().split(/\s+/).filter(x => x);
total += tokens.length;
}
return total;
}
}
A few details are worth knowing:
/\s+/is a regular expression literal.\smatches one whitespace character, including a space and a tab, and the+means "one or more", so a double space or a tab followed by a space is a single separator. Splitting on the plain string" "would not do this:"a b".split(" ")gives["a", "", "b"], while"a b".split(/\s+/)gives["a", "b"].- The filter callback
x => xreturns the string itself, and JavaScript treats the empty string as false and any other string as true. That is why it removes only empty pieces. - The annotation
: string[]is a promise checked by the compiler. TypeScript erases it when it compiles to JavaScript, so it costs nothing at run time. - The return type is
number, and a JavaScriptnumberis a double, so counts stay exact for any realistic input.
Complexity
Every character of every line is looked at a constant number of times by trim, split and filter, so the time is O(n) where n is the total number of characters. Each line's pieces are built and thrown away before the next line, so the extra space is proportional to the longest line.
Edge cases and common mistakes
- Blank lines. Skipping the filter gives
1for""and for a line of only spaces. This is the most common bug in this lesson. - Skipping the trim.
" a b".split(/\s+/)starts with an empty piece, so the line would count 3 words instead of 2. The filter would rescue that case too, but the trim states the intent clearly. - Tabs. Because the pattern is
\s+, a line such as" a \t b "counts as 2 words. - No lines. With
[]the loop never runs and the method returns0.
Testing
| Input | Result |
|---|---|
["hello world", "foo bar baz", ""] | 5 |
[" a \t b ", " ", "x"] | 3 |
[] | 0 |
The next version builds on this one.
