LearnCoding

Rarest element

Warm-upHash map, Counting

Problem

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

Signature

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

Examples

The visible tests, as an interactive Python session would show them: each call and the value it should give.

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

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

Solve it in your own editor; nothing on this page runs code.

Hints

Counter in O(n); find the minimum count.

On ties, return the smallest value; raise ValueError for empty input.

Keep it deterministic — dict order is not stable enough for ties.

Reference solution

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.