18. Top K Frequent Elements
mediumAsked at LINEReturn the k most frequent elements from an array — LINE uses this to gauge whether you reach for bucket sort by frequency, the same shape behind top-k sticker ranking.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an integer array nums and an integer k, return the k most frequent elements in any order. Your solution must run in better than O(n log n) time.
Constraints
1 <= nums.length <= 10^5k is in the range [1, number of unique elements]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 frequencies in a map, sort the unique keys by descending frequency, take the first k.
- Time
- O(n log n)
- Space
- O(n)
const c=new Map();
for(const x of nums) c.set(x,(c.get(x)||0)+1);
return [...c.entries()].sort((a,b)=>b[1]-a[1]).slice(0,k).map(e=>e[0]);Tradeoff:
2. Bucket sort by frequency
Count frequencies, then index buckets[freq] = [keys]. Scan buckets from high frequency down and collect until you have k elements. Linear in n because frequency is bounded by n.
- 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, f] of count) buckets[f].push(num);
const out = [];
for (let f = buckets.length - 1; f >= 0 && out.length < k; f--) {
for (const n of buckets[f]) {
out.push(n);
if (out.length === k) break;
}
}
return out;
}Tradeoff:
LINE-specific tips
At LINE, mention that ranking top-k stickers per chat room by usage frequency is the production version of this exact pipeline — sticker-delivery framing wins.
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 LINE interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →