Count how often each word appears in a sentence with split() and a dictionary in O(n). Practise Counter, defaultdict and dict.get in Python.
The problem
Return a dictionary mapping each word in sentence (split on whitespace) to how many times it appears. Words are case-sensitive.
Examples
Example 1
Input
word_frequency('python is easy and python is powerful')Expected output
{'python': 2, 'is': 2, 'easy': 1, 'and': 1, 'powerful': 1}Example 2
Input
word_frequency('a a a')Expected output
{'a': 3}
+ 2 hidden tests on Submit.
Edge cases to ask about
- Empty sentence
- Repeated spaces
- Case
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 measure your code against the optimal one at growing input sizes.
Pick both to reveal the answer.
Measure it
Runs the function on inputs of size 250 up to 16,000 and records the time and peak memory. Slow solutions stop early — a short curve is itself the answer.
From brute force to optimal
The progression an interviewer wants to hear, one step at a time.
| Approach | Time | Space | Idea |
|---|---|---|---|
| list.count per word | O(w²) | O(w) | Recounts for each word. |
| bestOne pass with a dict | O(n) | O(w) | Or Counter(sentence.split()). |
Walkthrough of the optimal approach (try it yourself first)
Split on whitespace, then count with a dict. In production you would also normalise case and strip punctuation — say that, then do what the question asks.
Complexity: O(n) time, O(w) space. split() and the counting loop are both linear in the sentence length; w distinct words are stored.
Reveal the reference solution
def word_frequency(sentence): freq = {} for word in sentence.split(): freq[word] = freq.get(word, 0) + 1 return freq
Follow-ups interviewers ask
- Top 3 most frequent words.
- Process a file too big for memory.
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of Word Frequency Count in Python?
The optimal solution runs in O(n) time and O(w) auxiliary space. split() and the counting loop are both linear in the sentence length; w distinct words are stored.
What is the brute-force approach, and how do you optimise it?
list.count per word: O(w²) time, O(w) space. Recounts for each word. One pass with a dict: O(n) time, O(w) space. Or Counter(sentence.split()).
What follow-up questions do interviewers ask about Word Frequency Count?
Top 3 most frequent words. Process a file too big for memory.
