Problem overview
The method countWords(lines) is the word-count half of the Unix wc tool. It receives an array of strings and returns one integer: the number of words across all the lines. A word is a run of characters without spaces or tabs, so any amount of whitespace between words counts as a single separator, and whitespace at the start or end of a line is ignored.
For ["hello world", "foo bar baz", ""] the lines contribute 2, 3 and 0 words, so the answer is 5. A line that is empty or holds only whitespace adds 0, and an empty array gives 0.
Approach: split each line, then count the real pieces
The natural plan is to handle one line at a time: turn the line into an array of words, add that array's length to a running total, and return the total at the end. The only difficulty is turning a line into words correctly.
line.split(" ") is not enough. It cuts at every single space, so two spaces in a row create an empty piece, and tabs are not separators at all. The regular expression /\s+/ fixes both: \s matches any whitespace character (space, tab and others) and + means "one or more", so a whole run of whitespace is one cut.
Two edge pieces remain. Leading whitespace makes split start with an empty string, which is why the line is trimmed first. And splitting an empty string does not give an empty array: it gives [""], one empty piece. The same happens for a line that is only spaces, once it has been trimmed. Filtering out the empty pieces turns those cases into 0 words.
Step by step
- Create
totalwithletand set it to 0. It is a running sum, so it must start at zero before any line is read. - Loop over the lines with
for...of.for (const line of lines)hands you each string directly, with no index to manage. - Build
tokens. Trim the line, split it on/\s+/, then keep only the pieces that are not empty withfilter(x => x). An empty string is falsy, so the callback returns a falsy value for it and the filter drops it. - Add
tokens.lengthtototal, still inside the loop, once per line. - Return
totalafter the loop, not inside it. A return inside the loop would stop after the first line.
The solution in JavaScript
class Solution {
countWords(lines) {
let total = 0;
for (const line of lines) {
const tokens = line.trim().split(/\s+/).filter(x => x);
total += tokens.length;
}
return total;
}
}
Details worth knowing:
constinfor (const line of lines)is fine: each pass creates a fresh binding for the current line.splitwith a regular expression is the reason tabs and repeated spaces are handled. Splitting on the string" "would give"a b".split(" ")equal to["a", "", "b"], an empty piece in the middle.- The filter is not optional. For a blank line,
"".split(/\s+/)is[""]and" ".trim().split(/\s+/)is[""]too. Without the filter each blank line would count as one word.
Complexity
Every character of every line is looked at a constant number of times (trimming, splitting, filtering), so the time is O(n), where n is the total number of characters. Each line's array of words is temporary, so the extra space is proportional to the longest line.
Edge cases and common mistakes
- Forgetting the filter. An empty line would then add 1 instead of 0.
- Forgetting
trim(). A line like" a b"would split into["", "a", "b"]; the filter would rescue the count, but trimming first keeps the code clear about its intent. - Splitting on
" "only. Tabs stay inside words and double spaces create phantom pieces. - Returning inside the loop, which stops at the first line.
Testing
| lines | result |
|---|---|
["hello world", "foo bar baz", ""] | 5 |
[" a \t b ", " ", ""] | 2 |
[] | 0 |
