Ctrl K

Most Common Values

Medium
You are given an integer array values and a number count. Find the count distinct values that occur in the array most often and return them in any order. The answer is guaranteed to be unique: the value ranked count-th by frequency occurs strictly more often than any value left out of the answer. Aim for better than O(n log n) time.
Example 1
values=[4, 7, 4, -2, 7, 4, 9], count=2 → [4, 7]

4 appears three times, 7 twice, -2 and 9 once each. The two most frequent are 4 and 7.

Example 2
values=[3, 3, 0, 0, 0, 5], count=1 → [0]

0 is the most frequent, with three occurrences.

Example 3
values=[6, 1, 6, 1, 2], count=3 → [6, 1, 2]

count equals the number of distinct values, so all three are returned.

Constraints
  • 1 ≤ length of values ≤ 10⁵
  • -10⁴ ≤ values[i] ≤ 10⁴
  • 1 ≤ count ≤ number of distinct values in values
  • The set of the count most frequent values is uniquely determined
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsMost Searched Words MediumK-th Highest Score MediumCharacters Grouped by Count MediumJobs With a Cooldown MediumHand-Rolled Sort Medium
loading Python…
Input
values=[4, 7, 4, -2, 7, 4, 9], count=2
Expected
[4, 7]

Run checks the first 3 tests in your browser. Submit checks all 22 tests on the server, hidden ones included.