21. Top K Frequent Elements
easyAsked at TripadvisorReturn the k most frequent values in an array — Tripadvisor applies this exact heap/bucket pattern to surface the top-k trending destinations or most-reviewed attractions on their homepage.
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]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. Sort by frequency
Count frequencies with a hash map, then sort the unique elements by frequency 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(([val]) => val);
}Tradeoff:
2. Bucket sort (optimal)
Build frequency buckets indexed by count (max index = n). Iterate buckets from highest to lowest, collecting elements until k are gathered. Beats O(n log n) 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 [val, count] of freq) buckets[count].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:
Tripadvisor-specific tips
Tripadvisor's recommendation team cares deeply about ranking — this problem is a direct proxy for how you'd rank destinations by review count or booking frequency. Interviewers expect you to land on the bucket-sort O(n) solution or at least articulate why it beats a heap approach in this case. Bonus points if you mention that in streaming analytics (real-time trending destinations), a min-heap of size k is often more practical than bucket sort.
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 Tripadvisor interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →