22. Top K Frequent Elements
mediumAsked at BookingReturn the k most frequent elements from an array — Booking's search team applies this pattern to surface the top-k most-booked destinations or properties for a given city query.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an integer array nums and an integer k, return the k most frequent elements. The answer may be returned in any order.
Constraints
1 <= nums.length <= 10^5k is in the range [1, the number of unique elements in nums]The answer is unique — there is only one set of k most frequent 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 frequencies with a hash map, sort unique elements by count descending, return 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 (linear)
Frequencies range [1..n]. Create n+1 buckets indexed by frequency; reverse-scan to collect top k. O(n) total.
- 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:
Booking-specific tips
Booking processes millions of search queries daily and the bucket-sort approach gets attention in systems design follow-ups — it avoids the log factor and scales with data. Be ready to explain why the bucket index equals frequency, not value.
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 Booking interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →