Top K Frequent Elements

MediumHeaps

Given an array of integers nums and a number k, return the k values that appear most often in nums.

The values can come back in any order. Every test has exactly one right set of k values, so there are no ties at the cut.

Examples

Example 1
Input:  nums = [4, 4, 4, 7, 7, 2], k = 2
Output: [4, 7]

4 appears three times and 7 twice; 2 only once.

Example 2
Input:  nums = [9], k = 1
Output: [9]

The only value is the most frequent one.

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • -10⁴ ≤ nums[i] ≤ 10⁴
  • k is between 1 and the number of different values.
  • The answer is unique.

Stuck?

Hint 1

First count how often each value appears with a Map. The question is then which k counts are the largest.

Hint 2

Sorting the counts costs O(n log n). To do better, put each value in a bucket indexed by its count (no count exceeds n), then read the buckets from the top down until you have k values.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur