19. Top K Frequent Elements
mediumAsked at Riot GamesReturn the k most frequent elements in an array — a Riot favorite for telemetry-rollup and anti-cheat anomaly detection pipelines.
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 and may assume the answer is unique.
Constraints
1 <= nums.length <= 10^5k is in the range [1, number of unique elements]
Examples
Example 1
nums=[1,1,1,2,2,3], k=2[1,2]Example 2
nums=[1], k=1[1]Approaches
1. Hash + full sort
Count frequencies then sort all unique keys by count descending.
- Time
- O(n log n)
- Space
- O(n)
const c = new Map();
for (const n of nums) c.set(n, (c.get(n)||0)+1);
return [...c.entries()].sort((a,b)=>b[1]-a[1]).slice(0,k).map(e=>e[0]);Tradeoff:
2. Bucket sort by frequency
Use n+1 buckets indexed by frequency, then walk buckets from high to low collecting k items. Riot uses the same bucket trick to aggregate per-tick cheat-signal counts without log-factor sorts.
- Time
- O(n)
- Space
- O(n)
function topKFrequent(nums, k) {
const c = new Map();
for (const n of nums) c.set(n, (c.get(n)||0)+1);
const buckets = Array.from({length:nums.length+1},()=>[]);
for (const [v,f] of c) buckets[f].push(v);
const out = [];
for (let i=buckets.length-1; i>=0 && out.length<k; i--) {
for (const v of buckets[i]) { out.push(v); if (out.length===k) break; }
}
return out;
}Tradeoff:
Riot Games-specific tips
Riot rewards candidates who recognize bucket sort's O(n) win when counts are bounded — the same constraint their anti-cheat heuristic counters operate under per server tick.
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 Riot Games interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →