19. Top K Frequent Elements
mediumAsked at Byju'sReturn the k most frequent values in an integer array.
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 algorithm's time complexity must be better than O(n log n) where n is the array's size.
Constraints
1 <= nums.length <= 10^5k is in the range [1, number of unique elements]
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 map, then sort entries by descending frequency.
- Time
- O(n log n)
- Space
- O(n)
const m=new Map();
for(const n of nums) m.set(n,(m.get(n)||0)+1);
return [...m.entries()].sort((a,b)=>b[1]-a[1]).slice(0,k).map(e=>e[0]);Tradeoff:
2. Bucket sort by count
Count frequencies, then bucket values by their count index. Walk buckets from highest to lowest and pull k values out.
- Time
- O(n)
- Space
- O(n)
function topKFrequent(nums, k) {
const count = new Map();
for (const n of nums) count.set(n, (count.get(n) || 0) + 1);
const buckets = Array.from({length: nums.length + 1}, () => []);
for (const [num, c] of count) buckets[c].push(num);
const res = [];
for (let i = buckets.length - 1; i >= 0 && res.length < k; i--)
for (const num of buckets[i]) {
res.push(num);
if (res.length === k) break;
}
return res;
}Tradeoff:
Byju's-specific tips
Byju's recommendation team uses top-k frequency aggregation for the 'most-watched lesson' carousel, so cite that during the design walk-through.
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 Byju's interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →