11. Count the Number of Words in a String

Difficulty:EasyPattern:String Traversal / SplittingTime:O(n)Space:O(n)

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:

  1. Remove leading and trailing whitespace.
  2. If the resulting string is empty, return 0.
  3. Split the string using whitespace as the delimiter.
  4. 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: 3
There 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.