6. Top K Frequent Elements

Return the k most frequent values in nums, in any order. The answer is guaranteed to be unique.

Example 1

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

Example 2

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

Constraints

  • 1 ≤ k ≤ number of distinct values
Hint 1

Count frequencies first.

Hint 2

A frequency can be at most n, so you can bucket values by frequency instead of sorting.

Hash TableBucket SortHeap