Count the words in a string correctly even with leading, trailing and repeated spaces, using split(). A quick Python string-handling interview check.
The problem
Return the number of words in s, where words are separated by any amount of whitespace.
Examples
Example 1
Input
count_words('Python is fun')Expected output
3
Example 2
Input
count_words(' many spaces here ')Expected output
3
+ 3 hidden tests on Submit — tabs and newlines count as whitespace.
Edge cases to ask about
- Only spaces
- Tabs/newlines
Hints
0/3How an interviewer scores this
0/9Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.
Complexity Lab
What does this cost as n grows?
Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.
Pick both to reveal the answer.
From brute force to optimal
The progression an interviewer wants to hear, one step at a time.
| Approach | Time | Space | Idea |
|---|---|---|---|
| len(s.split()) | O(n) | O(n) | A manual state machine counting word starts uses O(1) space. |
Walkthrough of the optimal approach (try it yourself first)
len(s.split()). With no argument, split() treats any run of spaces, tabs or newlines as one separator and ignores the ends. s.split(" ") would count empty strings between double spaces.
For O(1) extra space, count positions where a non-space follows a space (or the start).
Complexity: O(n) time, O(n) space. split() scans the string once and stores the words.
Reveal the reference solution
def count_words(s): return len(s.split())
Follow-ups interviewers ask
- Count words without building a list.
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of Count the Words in a String in Python?
The optimal solution runs in O(n) time and O(n) auxiliary space. split() scans the string once and stores the words.
What follow-up questions do interviewers ask about Count the Words in a String?
Count words without building a list.
