21. Top K Frequent Elements
mediumAsked at IndeedReturn the k most frequent elements — a core primitive in Indeed's trending search query and popular job-title surfacing pipelines.
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. The answer is guaranteed to be unique.
Constraints
1 <= nums.length <= 10^5k is in the range [1, the number of unique elements in the array]The answer is guaranteed to be unique
Examples
Example 1
nums = [1,1,1,2,2,3], k = 2[1,2]Example 2
nums = [1], k = 1[1]Approaches
1. Sort by frequency
Count with a hash map then sort entries by count descending and take the first k.
- 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(e=>e[0]);
}Tradeoff:
2. Bucket sort (O(n))
Place elements into frequency buckets indexed 0..n; scan from the highest bucket down to collect k elements without any comparison sort.
- 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, cnt] of freq) buckets[cnt].push(num);
const res = [];
for (let i = buckets.length-1; i >= 0 && res.length < k; i--) {
for (const n of buckets[i]) { res.push(n); if (res.length===k) break; }
}
return res;
}Tradeoff:
Indeed-specific tips
Indeed expects bucket sort for this problem; relate it to their real-time trending-search counter that must produce top-k results in a single pass over impression logs.
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 Indeed interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →