Find Mode

A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
medium
Seniority
L3

Problem

You're working through an event log flattened into a plain list of event types. Return the type that occurs most often.

One value appears more than the rest.

Example 1

Input:

lst = ["a","b","a","c","a","b"]

Output:

"a"

Example 2

Input:

lst = ["c","a","b","a","b"]

Output:

"a"

Worked solution and explanation

What this problem really is

Strip the event-log costume and this is a frequency count with a first-occurrence tie-break bolted on. Anyone can tally counts in a dict; what separates candidates is whether the tie rule survives their choice of max. Take the max over (count, value) pairs and Python breaks the tie by comparing the values themselves, so on ['c', 'a', 'b', 'a', 'b'] you get 'b' instead of 'a'. Take it over set(lst) and a tie goes to whatever the set happens to iterate first, which for strings can change from run to run. Both pass every untied input, so the bug hides until a tie shows up.


How to get there

Step 1: Count occurrences in a single pass

Walk the list once and accumulate a count per element. Because you insert keys in the order you first meet them, the dict already remembers first-occurrence order for free.

Step 2: Pick the max in first-appearance order, keeping strict inequality

Walk the elements in the order they first appeared (the original list works, and so does the insertion-ordered dict) and keep the element whose count is strictly greater than the best so far. Strictly greater is the whole trick: a tie never displaces the incumbent, so the first-seen element stays on top.


The solution

Frequency map with first-occurrence tiebreaking
def most_frequent(lst):
    counts = {}
    for item in lst:
        counts[item] = counts.get(item, 0) + 1
    best = lst[0]
    best_count = counts[best]
    for item in lst:
        if counts[item] > best_count:
            best = item
            best_count = counts[item]
    return best

Common follow-up questions