☰ All problems

13. Top K Frequent Elements

Given an integer array nums and an integer k, return the k values that occur most often in nums. You may return them in any order.

The tests guarantee that the answer is unique: there is never a tie in frequency between the k-th most frequent value and the next one.

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

Explanation: 4 occurs three times and 6 twice; 9 occurs only once.

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

Explanation: Frequencies are 5 → 3, 3 → 2, 2 → 1, 1 → 1.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • 1 <= k <= the number of distinct values in nums
  • The answer is unique.

Follow-up: Can you beat O(n log n), where n is the length of the array?

💡 Hint 1

First count how many times each value occurs with a hash map.

💡 Hint 2

Sorting the distinct values by count costs O(m log m). A min-heap of size k brings that to O(m log k).

💡 Hint 3

A frequency is always between 1 and n. Put each value into a bucket indexed by its count, then read buckets from the highest count down until you have k values.

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number[]}
 */
function topKFrequent(nums, k) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc