16. Top K Frequent Elements
mediumAsked at GlassdoorSurfacing the highest-rated companies out of millions of reviews is Glassdoor's bread and butter — this heap-based top-K problem tests whether you can rank by frequency without sorting everything first.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Constraints
1 <= nums.length <= 10^5k is in the range [1, the number of unique elements in nums]The answer is guaranteed to be unique
Examples
Example 1
nums = [1,1,1,2,2,3], k = 2[1,2]Explanation: 1 appears 3 times, 2 appears twice — both beat 3's single occurrence.
Example 2
nums = [1], k = 1[1]Approaches
1. Sort by frequency
Count frequencies with a map, then sort entries by count descending and take the first k. O(n log n) due to the sort.
- Time
- O(n log n)
- Space
- O(n)
function topKFrequent(nums, k) {
const freq = new Map();
for (const n of nums) freq.set(n, (freq.get(n) || 0) + 1);
return [...freq.entries()]
.sort((a, b) => b[1] - a[1])
.slice(0, k)
.map(([num]) => num);
}Tradeoff:
2. Bucket sort (linear)
Frequency can range from 1 to n, so use bucket indices. Place each element in the bucket at index equal to its count, then scan buckets right-to-left collecting k elements. O(n) time.
- Time
- O(n)
- Space
- O(n)
function topKFrequent(nums, k) {
const freq = new Map();
for (const n of nums) freq.set(n, (freq.get(n) || 0) + 1);
const buckets = Array.from({ length: nums.length + 1 }, () => []);
for (const [num, count] of freq) buckets[count].push(num);
const result = [];
for (let i = buckets.length - 1; i >= 0 && result.length < k; i--) {
for (const num of buckets[i]) {
result.push(num);
if (result.length === k) break;
}
}
return result;
}Tradeoff:
Glassdoor-specific tips
Glassdoor's ranking features depend on surfacing high-signal content quickly. Show that you know the bucket-sort trick drops the complexity to O(n) — interviewers there frequently push back with 'can you do better than n log n?' if you stop at the sort approach. Tie your explanation to how frequency caps at array length, which makes bounded buckets possible.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Top K Frequent Elements and other Glassdoor interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →