# Find Mode

> One value appears more than the rest.

Canonical URL: <https://datadriven.io/problems/find_mode>

Domain: Python · Difficulty: medium · Seniority: L3

## Problem

Given a list, return the most frequent element. If tied, return the element whose first occurrence is earliest in the list.

## Worked solution and explanation

### Why this problem exists in real interviews

Finding the most frequent element tests **frequency counting** with a **tiebreaking rule** based on first occurrence. It checks whether you can combine dict accumulation with careful result tracking.

---

### Break down the requirements

#### Step 1: Count occurrences of each element

Build a frequency dict mapping each element to its count.

#### Step 2: Find the element with the highest count, breaking ties by first occurrence

Track both the maximum count and the element that achieved it first.

---

### The solution

**Frequency map with first-occurrence tiebreaking**

```python
def most_frequent(lst):
    counts = {}
    for item in lst:
        if item not in counts:
            counts[item] = 0
        counts[item] += 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
```

> **Time and Space Complexity**
>
> **Time:** O(n) for two passes: one to count, one to find the max with first-occurrence tiebreaking.
> 
> **Space:** O(k) where k is the number of unique elements in the frequency dict.

> **Interviewers Watch For**
>
> The tiebreaking strategy. Iterating through the original list (not the dict) to find the max ensures first-occurrence wins. Iterating the dict keys does not guarantee order in all situations.

> **Common Pitfall**
>
> Iterating over `counts.items()` to find the max. While dict insertion order is preserved in Python 3.7+, the intent is clearer when you iterate the original list.

---

## Common follow-up questions

- What if you needed all elements that share the maximum frequency? _(Tests collecting all items with the max count rather than just the first.)_
- How would you find the top-k most frequent elements? _(Tests sorting the frequency dict or using a heap.)_
- What if the data is streaming and you cannot store all elements? _(Tests approximate algorithms like Count-Min Sketch or Space-Saving.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/find_mode)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.