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 given items, a device log from one sensor shift. Each entry is a code the sensor reported. Return every code that appears the most times, 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: it 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(int) keeps the increment clean by defaulting missing codes to zero.

Step 2: Find the peak count

Take the largest of those tallies with max(counts.values()). 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. An empty log has no peak at all, so return early before this line.

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, and where skipping the sort leaks the log's own order into the answer.


The solution

Frequency counting with tie-inclusive mode extraction
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