Top K Frequent Elements
1 approach, code in every language
Problem description
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 unique
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Most Reported Calibration Offsets is our own problem on the technique behind Top K Frequent Elements: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free