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

Case-normalized frequency accumulation
def word_frequencies(text: str) -> dict:
    words = text.lower().split()
    freq = {}
    for word in words:
        freq[word] = freq.get(word, 0) + 1
    return freq

Common follow-up questions