Build a tiny version of the Unix wc -w command. Given a list of lines, return the total number of words (whitespace-separated tokens) across all lines as an integer.
Function signature:
def countWords(self, lines: List[str]) -> int:
Example:
Input: lines = ["hello world", "foo bar baz", ""] Output: 5
The empty string contributes 0 words, "hello world" contributes 2, and "foo bar baz" contributes 3. Total: 5.
Words are separated by one or more spaces or tabs, and leading or trailing whitespace is ignored. A line with no words (empty, or only whitespace) contributes 0, and an empty list of lines gives 0. The input is plain ASCII text.
Iterate over the lines and accumulate the word count. The trick is splitting on whitespace correctly so that empty / whitespace-only lines contribute zero.
Calling
str.split() with no arguments handles whitespace beautifully — multiple spaces are treated as one, and an empty string produces an empty list.
total += len(line.split())
The full solution:
class Solution:
def countWords(self, lines):
total = 0
for line in lines:
total += len(line.split())
return total
Free plan: 30 tutor messages. Premium is unlimited.
