Katkat

Return the Most Frequent Integer with a Stable Tie-Breaker

ByteDanceSoftware Engineer · Technical Screen

Last updated

Implement a frequency-based selection over a large integer array: return the most common value, using the numerically smallest value to break ties. Preserve the input and return the value itself rather than its count or position.

Return the Most Frequent Integer with a Stable Tie-Breaker

Given a nonempty integer array, return the value that appears most often. If several values have the same highest frequency, return the numerically smallest one.

Function Contract

def most_frequent_smallest(values: list[int]) -> int:
 ...

Constraints

  • 1 <= len(values) <= 200_000
  • -10**9 <= values[i] <= 10**9
  • Do not mutate the input.
  • Return the integer value, not its frequency or index.

Examples

values = [4, 1, 4, 2, 2]
result = 2

Both 2 and 4 occur twice, so the smaller value is returned.

values = [-1, -1, 3]
result = -1