Quick Overview

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

Company: Bytedance

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Technical Screen

# 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 ```python 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 ```text values = [4, 1, 4, 2, 2] result = 2 ``` Both `2` and `4` occur twice, so the smaller value is returned. ```text values = [-1, -1, 3] result = -1 ```

Quick Answer: 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.

Implement most_frequent_smallest(values). Return the most frequent value in the non-empty integer array. When several values tie for the highest frequency, return the numerically smallest one. Do not mutate the input.

Constraints

  • 1 <= len(values) <= 200,000
  • -10^9 <= values[i] <= 10^9
  • Do not mutate values.

Examples

Input: ([1],)

Expected Output: 1

Explanation: Checks unique maxima and numeric tie-breaking, including negatives.

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

Expected Output: 2

Explanation: Checks unique maxima and numeric tie-breaking, including negatives.

Hints

  1. Count each value with a hash map.
  2. Compare candidates first by larger count and then by smaller numeric value.

Loading coding console...