347. Top K Frequent Elements
mediumAsked at DuolingoReturn the k most frequent elements from an array — the heap or bucket-sort technique Duolingo's recommendation engine uses to surface the k words a learner encounters most so they can be promoted to the next spaced-repetition review slot.
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. It is guaranteed that the answer is 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 Map, then sort entries 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(e => e[0]);
}Tradeoff:
2. Optimal — bucket sort O(n)
Place each number into a frequency bucket (index = frequency), then read buckets from highest to lowest until k elements are collected.
- 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 = new Array(nums.length + 1).fill(null).map(() => []);
for (const [num, cnt] of freq) buckets[cnt].push(num);
const result = [];
for (let i = buckets.length - 1; i >= 1 && result.length < k; i--) {
for (const num of buckets[i]) {
result.push(num);
if (result.length === k) return result;
}
}
return result;
}Tradeoff:
Duolingo-specific tips
Duolingo interviewers ask this to test whether you know heap vs. bucket sort — both are acceptable but the O(n) bucket approach shows deeper understanding. The key insight: maximum frequency is bounded by n, so bucket indices never overflow. Tie this to Duolingo's use case: surfacing the k words a user has seen most often to schedule them for active recall. Interviewers often follow up with 'What if the stream is infinite?' — that is where a min-heap of size k becomes the right answer.
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 Duolingo interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →