Top K Frequent Elements
Medium · Arrays & Hashing
Given an integer array nums and an integer k, return the k elements that occur most frequently in the array. You may return the answer in any order. It is guaranteed that among all elements there is a well-defined set of k elements with the highest frequencies, so no tie-breaking ambiguity needs to be resolved.
Examples
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Why: 1 appears 3 times, 2 appears 2 times, 3 appears once; the two most frequent are 1 and 2.
Input: nums = [1], k = 1
Output: [1]
Why: The only element present is 1, so it is trivially the most frequent.
Input: nums = [4,4,4,4,5,5,6], k = 2
Output: [4,5]
Why: 4 occurs 4 times and 5 occurs 2 times, more than 6 which occurs once.
Constraints
1 <= nums.length <= 10^5; -10^4 <= nums[i] <= 10^4; k is guaranteed to be valid (1 <= k <= number of distinct elements)
Practise it by voice
Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.
Practise Top K Frequent Elements
This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Top K Frequent Elements. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.