Count the Number of Words in a Given String
Problem
Given a string s, return the number of words it contains. A word is a maximal sequence of non-space characters. The string may contain leading, trailing or multiple consecutive spaces, and may be empty.
Input / Output
- Input: string
s. - Output: integer word count.
Examples
Example 1
Input: s = "the quick brown fox"
Output: 4
Example 2
Input: s = " hello world "
Output: 2
Example 3
Input: s = "" or s = " "
Output: 0
Constraints
0 <= s.length <= 10^5
Approach
A word starts at every index i where s[i] is not a space and (i == 0 or s[i-1] is a space). Count those positions in one pass:
count = 0
for i in range(n):
if s[i] != ' ' and (i == 0 or s[i-1] == ' '):
count += 1
This handles all the whitespace edge cases without allocating a list, unlike len(s.split()), which is fine in practice but is not what a "do it manually" interviewer wants.
Extensions: treat tabs and newlines as separators (isspace()), or count only words made of letters.
Complexity
- Time: O(n)
- Space: O(1)
Reference solution (Python)
def count_words(s):
count = 0
for i, c in enumerate(s):
if not c.isspace() and (i == 0 or s[i - 1].isspace()):
count += 1
return count
Test cases
| Input | Expected |
|---|---|
"the quick brown fox" | 4 |
" hello world " | 2 |
"" | 0 |
"a" | 1 |