19. Top K Frequent Elements
mediumAsked at InstacartReturn the k most frequently occurring integers — Instacart uses frequency ranking everywhere from surfacing top-ordered items to ranking stores by pickup volume in real-time catalog queries.
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^5-10^4 <= nums[i] <= 10^4k is in the range [1, 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 frequencies with a hash map, then sort the unique elements by their count descending and return 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.keys()].sort((a, b) => freq.get(b) - freq.get(a)).slice(0, k);
}Tradeoff:
2. Bucket sort (linear)
Map each element to its frequency, then place elements into buckets indexed by frequency. Collect from the highest-frequency bucket down until k elements are gathered.
- 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);
// buckets[i] = list of elements that appear exactly i times
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 >= 1 && result.length < k; i--) {
result.push(...buckets[i]);
}
return result.slice(0, k);
}Tradeoff:
Instacart-specific tips
Instacart's catalog and recommendation pipelines rank items by order frequency under tight latency budgets. The bucket-sort approach signals you can reason about frequency bounds (max freq = n) to shave a log factor — interviewers respond well when you call that out before coding.
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 Instacart interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →