---
title: Rarest element
url: https://gurkanozkan.ai/learn/coding/mle-rarest-element-34/
markdown: https://gurkanozkan.ai/learn/coding/mle-rarest-element-34.md
kind: coding
difficulty: Warm-up
topics:
  - Hash map
  - Counting
json: https://gurkanozkan.ai/api/learn/coding/mle-rarest-element-34.json
robots: noindex
---

# Rarest element

Return the least frequent value in `nums`; on ties return the smallest such value. Raise `ValueError` for an empty list.

## Signature

```python
def rarest(nums: list[int]) -> int: ...
```

## Examples

Each call and the value it should give.

```python
>>> rarest([4, 4, 1, 2, 2]) == 1
True

>>> rarest([3, 1, 3, 1]) == 1
True
```

## Hints

1. Counter in O(n); find the minimum count.
2. On ties, return the smallest value; raise ValueError for empty input.
3. Keep it deterministic — dict order is not stable enough for ties.

## Reference solution

```python
from collections import Counter

def rarest(nums):
    if not nums:
        raise ValueError("empty")
    c = Counter(nums)
    m = min(c.values())
    return min(v for v, n in c.items() if n == m)
```

## What a strong solution covers

- Counter in O(n) (better than the O(n log n) the prompt allowed).
- Deterministic tie-break.
- Discusses streaming or approximate variants for huge inputs.

## Common mistakes

- arbitrary dict order on ties
- not handling empty input.
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
