Top K Frequent Elements

Medium Heap / Priority Queue AI round

nums is a list of whole numbers, and k is a whole number.

The frequency of a number is how many times it appears in nums. The numbers that appear most often are the ones with the highest frequencies.

Return the k numbers of nums with the highest frequencies, each one once, in any order. The tests are made so that exactly one set of k numbers is right: no number outside it appears as often as the least frequent number inside it.

Example 1

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

4 appears 4 times, 6 appears 3 times, 9 appears 2 times and 1 once, so the two most frequent numbers are 4 and 6.

Example 2

Input: nums = [5], k = 1
Output: [5]

Example 3

Input: nums = [-2,-2,7,7,7,0,0,-2,7], k = 1
Output: [7]

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • -10⁶ ≤ nums[i] ≤ 10⁶
  • 1 ≤ k ≤ the number of different values in nums
  • Only one set of k numbers has the highest frequencies: the number with the k-th highest frequency appears more often than any number after it

Watch the explanation

More Heap / Priority Queue

All Heap / Priority Queue problems