Word Counter - Problem
Count the number of words in a sentence. A word is defined as a sequence of non-space characters.
Important: Handle multiple consecutive spaces between words and leading/trailing spaces properly.
For example:
"hello world"has 2 words" hello world "has 2 words (ignore extra spaces)""has 0 words" "has 0 words
Input & Output
Example 1 — Basic Case
$
Input:
sentence = "hello world"
›
Output:
2
💡 Note:
Two words separated by a single space: "hello" and "world"
Example 2 — Multiple Spaces
$
Input:
sentence = " hello world "
›
Output:
2
💡 Note:
Same two words but with leading, trailing, and multiple spaces between - still counts as 2 words
Example 3 — Empty String
$
Input:
sentence = ""
›
Output:
0
💡 Note:
Empty string contains no words
Constraints
- 0 ≤ sentence.length ≤ 104
- sentence consists of English letters, digits, and spaces ' '
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code