The One-Timers
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
- L4
Problem
Given a dict, return the sorted list of values that appear exactly once across all entries.
Values that never repeated.
Example 1
Input:
d = {"a":1,"b":2,"c":1,"d":3}Output:
[2,3]
Example 2
Input:
d = {"x":5,"y":5}Output:
[]
Worked solution and explanation
The trap hiding in 'exactly once'
Read this fast and it looks like a dedup: return the distinct values, sorted. So the hand reaches for sorted(set(d.values())) and moves on. That is the wrong answer. 'Appears exactly once' is a frequency filter, not a distinctness filter. On {"x": 5, "y": 5} the set trick returns [5]; the real answer is [], because 5 occurred twice. The real skill here is tallying how often each value shows up and keeping only the ones with a count of one. A set literally cannot express that, since it throws away the counts the moment you build it.
Break down the requirements
Step 1: Count how many times each value appears
Walk the dict and tally each value into a frequency map. The keys are irrelevant to the count; two different keys holding 5 push its tally to 2.
Step 2: Filter values with count exactly 1
Keep only the values whose tally is exactly 1. This is where the set-based approach silently fails: it keeps a repeated value as a single copy instead of dropping it entirely.
Step 3: Sort and return
Sort the survivors ascending and return them. When nothing has a count of 1, that is an empty list, not an error.
The solution
def the_one_timers(d):
value_counts = {}
for key in d:
val = d[key]
if val in value_counts:
value_counts[val] += 1
else:
value_counts[val] = 1
result = []
for val in value_counts:
if value_counts[val] == 1:
result.append(val)
result.sort()
return resultCommon follow-up questions
- What if you needed values appearing more than once? (Tests inverting the filter condition.)
- What if values were unhashable (e.g., lists)? (Tests converting to tuples for hashing or using a different counting strategy.)
- How would you return the keys that map to unique values? (Tests pairing the value frequency filter with key lookup.)