19. Top K Frequent Elements
easyAsked at EtsyReturn the k most frequent elements — the direct model behind Etsy's 'best-selling items in a category' ranking that drives the search results page.
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 the array]It is guaranteed that the answer is unique
Examples
Example 1
nums = [1,1,1,2,2,3], k = 2[1,2]Example 2
nums = [1], k = 1[1]Approaches
1. Brute force sort
Count frequencies with a map, convert to array of [value, count] pairs, sort descending by count, slice 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(e => e[0]);
}Tradeoff:
2. Bucket sort (linear)
After building the frequency map, create n+1 buckets indexed by frequency. Place each unique element in its frequency bucket. Walk buckets from high to low, collecting elements until k are gathered. 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 [val, cnt] of freq) buckets[cnt].push(val);
const result = [];
for (let i = buckets.length - 1; i >= 0 && result.length < k; i--) {
result.push(...buckets[i]);
}
return result.slice(0, k);
}Tradeoff:
Etsy-specific tips
Etsy uses this pattern for real-time trending categories. Mention the bucket-sort trick explicitly — it shows you recognize when sorting is unnecessary because the domain (frequency 1..n) gives you a natural index. The interviewer will often ask you to stream updates; be ready to switch to a min-heap approach for that variant.
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 Etsy interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →