KatInterview

Find the Modal Number, Smallest on a Tie

Arrays & HashingAuto-graded · 25 test cases
EasyAuto-gradedArrays & Hashinghash-mapcountingtie-breaking

Last updated

Tests frequency counting with a hash map and a deterministic numeric tie-break, returning the value itself without altering the input list.

Find the Modal Number, Smallest on a Tie

You are given a non-empty list of integers. Determine which value occurs the greatest number of times in the list and return that value.

If more than one value shares the greatest number of occurrences, return the numerically smallest among them. The tie is decided purely by numeric value. The position at which a value first appears in the list has no influence on the answer.

The function must return the integer itself, not how many times it appears and not its position in the list. The input list must be left unchanged.

Function

def modal_smallest(nums: List[int]) -> int:

Constraints

  • 1 <= len(nums) <= 200_000
  • -10**9 <= nums[i] <= 10**9
  • The list is never empty.
  • Do not modify nums.
  • Return a single integer: the value itself.

Examples

Example 1

Input: modal_smallest([4, 1, 4, 2, 2])

Output: 2

Example 2

Input: modal_smallest([-1, -1, 3])

Output: -1

Hints

Hint 1

Separate the work into two phases: first find how often each distinct value occurs, then decide which value wins.

Hint 2

A dictionary (or collections.Counter) gives you the occurrence count of every value in one pass. Then look at the largest count.

Hint 3

Collect only the values whose count equals that largest count and take their minimum. Do not rely on first-seen order or on Counter.most_common, since ties there are not resolved by numeric value.