The Dominant Signal
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
- Amazon
Problem
You're scanning a device log where each entry is a code a sensor reported during a shift. Return every code that shows up the most times, and when several tie for the top, return all of them in ascending order.
Hottest items in the transaction log. Ties included.
Example 1
Input:
items = [3,2,2,3,3,4]
Output:
[3]
Example 2
Input:
items = [4,4,2,2,1]
Output:
[2,4]
Worked solution and explanation
What this really is
This is find-all-modes wearing a sensor-log costume. The tempting move is to reach for the one built-in that looks like it does the whole job, a most-common-one call, and it is a trap: that hands back exactly one winner, so the moment two codes tie at the top frequency you have silently dropped one. The skill being probed is whether you split the job in two: find the peak count first, then collect everything that reaches it. Miss that and a log with a genuine tie comes back half-right, which is exactly the failure the interviewer is hunting for.
The three moves
Step 1: Count each code
Walk the log once and tally how many times each code appears. A running increment into a dict keyed by code does this in one pass; a defaultdict keeps the increment clean by defaulting missing codes to zero.
Step 2: Find the peak count
Take the largest of those tallies. This is a separate step from picking a winner, and keeping it separate is what makes ties fall out naturally: you now know the height of the peak without having chosen which code sits on it.
Step 3: Collect all codes at the peak, sorted
Keep every code whose tally equals the peak, then sort ascending. This is where single-winner solutions quietly lose the tied codes.
The solution
from collections import defaultdict
def most_frequent(items: list) -> list:
if not items:
return []
counts = defaultdict(int)
for code in items:
counts[code] += 1
peak = max(counts.values())
return sorted([code for code, count in counts.items() if count == peak])One pass to count, one to find the peak, one to filter and sort.
Common follow-up questions
- What if you needed the top-k most frequent codes, not just the peak? (Pushes toward a heap or a partial sort instead of a single max scan.)
- What if the tied codes had to come back in the order they first appeared? (Tests whether they preserve first-seen order instead of sorting.)
- How would this change if the log arrived as a stream too large to hold at once? (Tests streaming intuition when the whole log will not fit in memory.)