11. Count the Number of Words in a String
Given a string containing words separated by spaces, count the number of words.
How It Works & Algorithmic Design
A simple approach is to split the string into words after trimming surrounding whitespace:
- Remove leading and trailing whitespace.
- If the resulting string is empty, return
0. - Split the string using whitespace as the delimiter.
- Return the number of resulting words.
Why This Approach Works Best
For an easy-level problem, splitting provides a clear and readable solution. The time complexity is $O(n)$ where $n$ is the string length. The resulting word collection requires $O(n)$ space.
Example Walkthrough
Input:
"I love programming"The sentence contains three words.
Split:
["I", "love", "programming"]Whitespace separates the words.
Output:
3There are three words.
Answer: Count words
function countWords(str) {
const trimmed = str.trim();
if (trimmed === '') return 0;
return trimmed.split(/\s+/).length;
}💡 Trim the input and split it using whitespace.
Key Takeaways
- Whitespace should be handled carefully when counting words.
- Trimming and splitting makes the basic solution easy to understand.
- The operation takes O(n) time.