You are given an integer array and an integer k. Return the k values that occur most often in the array.
The result may be returned in any order, and the problem guarantees that the set of top-k values is unique. Aim for a solution that is faster than fully sorting the array by frequency.
Example 1
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
1 appears three times and 2 appears twice, so they are the two most frequent values.
Example 2
Input: nums = [1], k = 1
Output: [1]
There is only one distinct value, and it is the most frequent.
Constraints
1 <= nums.length <= 10^5-10^4 <= nums[i] <= 10^4k is in the range [1, the number of unique elements in the array]The answer is guaranteed to be uniqueSee the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI