70. Top K Frequent Elements
Count how often each distinct input value occurs and select the k values with the greatest counts. Report the selected values rather than their individual occurrences.
This course orders the result by decreasing frequency, then increasing numeric value for ties. Do not assume arbitrary tie order is accepted.
Example 1
Input
nums=[4,4,1,1,2,3], k=2
Output
[1,4]
Explanation: Both 1 and 4 occur twice, so smaller value 1 precedes 4.
Example 2
Input
nums=[−1,−1,2,3], k=3
Output
[−1,2,3]
Explanation: Frequency outranks numeric magnitude. The final two keys tie at count one.
Example 3
Input
nums=[], k=0
Output
fresh []
Explanation: The rank set is empty and no value sentinel is needed.
Constraints
0 <= nums.length <= 105-231 <= nums[i] <= 231 - 10 <= k <= number of distinct values
Hints
Hint 1
How many times does each distinct key occur?
Hint 2
Which selected candidate should be easiest to evict when the heap exceeds k?
Hint 3
Use the reverse of the final count/value rank for the heap root, trim after each insertion, and sort the survivors.
Submissions
Your recent submissions for this problem.
Checking sign-in…
Discussion
Ask a question or share an approach. Posts are public; avoid personal information and mark solution spoilers clearly.
No discussion yet. Start the conversation with a question about this problem.
Checking sign-in…
Run your code to check the sample cases, or submit it to check the full validation suite.
Count ties select smaller values
[4,4,1,1,2,3]
2
[1,4]