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
INPUTALGORITHMRESULT" hello world "Sentence with extra spaces1Trim leading/trailing spaces2Split by whitespace3Count resulting segmentshelloworld2words foundKey Insight:Use built-in string splitting methods to automatically handle multiple spacesand focus on counting actual word segments rather than manual character tracking.TutorialsPoint - Word Counter | Split Method Approach
Asked in
Google 25 Amazon 18 Microsoft 15
23.4K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen