The Word Inventory
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
- L6
- Asked in
- Natera
Problem
Given a list of words, return a dict with two keys. 'counts' maps each word to its frequency. 'unique' is the sorted list of words that appear exactly once.
Every word, twice over.
Example 1
Input:
words = ["apple","banana","apple","cherry","banana","date"]
Output:
{"counts":{"date":1,"apple":2,"banana":2,"cherry":1},"unique":["cherry","date"]}Example 2
Input:
words = ["x","x","x"]
Output:
{"counts":{"x":3},"unique":[]}Worked solution and explanation
Why this problem exists in real interviews
This tests frequency counting with a secondary filter for singletons. It combines dict accumulation with a filtering pass, a pattern common in data quality and analytics pipelines.
Break down the requirements
Step 1: Count word frequencies
Build a dict mapping each word to its occurrence count.
Step 2: Extract words appearing exactly once
Filter the frequency dict to find singletons and sort them alphabetically.
Step 3: Return both the counts dict and the unique list
Package both results in a dict with 'counts' and 'unique' keys.
The solution
def word_inventory(words: list) -> dict:
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
unique = []
for word in sorted(counts.keys()):
if counts[word] == 1:
unique.append(word)
result = {"counts": counts, "unique": unique}
return resultCommon follow-up questions
- What if you also needed words appearing exactly twice? (Tests parameterizing the frequency filter.)
- How would you make this case-insensitive? (Tests lowercasing words before counting.)
- How would you handle a stream of words that does not fit in memory? (Tests approximate frequency counting with Count-Min Sketch or similar probabilistic structures.)