Top K Frequent Elements
Medium Heap / Priority Queue AI round
nums is a list of whole numbers, and k is a whole number.
The frequency of a number is how many times it appears in nums. The numbers that appear most often are the ones with the highest frequencies.
Return the k numbers of nums with the highest frequencies, each one once, in any order. The tests are made so that exactly one set of k numbers is right: no number outside it appears as often as the least frequent number inside it.
Example 1
Input: nums = [4,9,4,6,9,4,6,4,6,1], k = 2
Output: [4,6]
4 appears 4 times, 6 appears 3 times, 9 appears 2 times and 1 once, so the two most frequent numbers are 4 and 6.
Example 2
Input: nums = [5], k = 1
Output: [5]
Example 3
Input: nums = [-2,-2,7,7,7,0,0,-2,7], k = 1
Output: [7]
Constraints
1 ≤ nums.length ≤ 10⁵-10⁶ ≤ nums[i] ≤ 10⁶1 ≤ k ≤the number of different values innums- Only one set of
knumbers has the highest frequencies: the number with thek-th highest frequency appears more often than any number after it
Practice this in an AI round
30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.
Your first AI round is free.
Watch the explanation
More Heap / Priority Queue
- Kth Largest Element in an ArrayAI round · Medium
- Reorganize StringAI round · Medium
- Task SchedulerMedium
- Sort Characters By FrequencyMedium
- K Closest Points to OriginMedium