Rarest element
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
TrueHints
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.