Top K Frequent Elements
Top K Frequent Elements is a medium coding interview question. You’re given an integer array nums and an integer k. Return the k values that appear most often in nums, in any order. Below are examples, the constraints and 3 hints; press Practice and Dana, the interviewer, asks it out loud while you answer in TypeScript, Python, Java, C++ or Go.
Updated · By InterviewMind
Free in your browser, no account.
The problem
Coding · Medium
You’re given an integer array nums and an integer k. Return the k values that appear most often in nums, in any order.
The answer is always unique, so there’s never a tie for the last of the k places. Aim for better than O(n log n) time.
Example 1
nums = [4,4,4,6,6,9], k = 2Output[4,6]4 appears three times and 6 twice, more than any other value.
Example 2
nums = [7], k = 1Output[7]Constraints
- 1 ≤ nums.length ≤ 10⁵
- -10⁴ ≤ nums[i] ≤ 10⁴
- 1 ≤ k ≤ the number of distinct values in nums
- The answer is unique
Hints
Open one at a time, and try the question again after each.
Hint 1
Count first: one pass with a hash map from each value to how often it appears. What’s left is picking the k largest counts.
Hint 2
A min-heap capped at k entries does that in O(n log k): push each value with its count, and pop the smallest when the heap grows past k. Or group values into buckets by count, which takes O(n).
Hint 3
If you bucket by count, you need n + 1 buckets, since one value can fill the whole array, as in [7]. Read the buckets from the highest count down and stop once you have k values.
Practice it out loud
In the practice room Dana reads the question aloud in your browser’s own voice, with captions, and you answer in the editor beside it, in TypeScript, Python, Java, C++ or Go. It can look like LeetCode, HackerRank, CoderPad or Codility, so the screen is the one you’ll meet. It’s free and needs no account. Run the InterviewMind desktop app beside it and it hears the question the way it hears a real call, so you can see what it would show you in the live round.
Practice this questionMore coding questions
- Merge Intervals · Medium
- LRU Cache · Medium
- Two Sum · Easy
- Valid Parentheses · Easy
- Longest Substring Without Repeating Characters · Medium
- Number of Islands · Medium
More on these rounds: Coding interview practice.