The Word Census
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L3
- Asked in
- Notion
Problem
Given a string of whitespace-separated words, return a dict mapping each distinct lowercased word to its count. (Test harness accepts any key order; note the expected output shows sorted-by-count which may not be guaranteed by dict iteration - be explicit: return a regular dict.)
Who said what - and how many times?
Example 1
Input:
text = "the cat sat on the mat"
Output:
{"the":2,"cat":1,"sat":1,"on":1,"mat":1}Example 2
Input:
text = "a a a b b"
Output:
{"a":3,"b":2}Worked solution and explanation
Why this problem exists in real interviews
This tests word frequency counting with case normalization. Building a frequency dict from text is fundamental to text processing pipelines, search indexing, and analytics.
Break down the requirements
Step 1: Split the string on whitespace and lowercase each word
Treat 'The' and 'the' as the same word.
Step 2: Count occurrences in a dict
Accumulate each word's count using dict operations.
The solution
def word_frequencies(text: str) -> dict:
words = text.lower().split()
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
return freqCommon follow-up questions
- How would you handle punctuation attached to words? (Tests stripping punctuation with `str.strip` or regex before counting.)
- How would you return only words above a frequency threshold? (Tests adding a filter after counting.)
- How would you process a file too large for memory? (Tests streaming line-by-line and accumulating counts incrementally.)