Skip to main content

22. Top K Frequent Elements

mediumAsked at Activision

Return the k most frequent elements — Activision uses this to gauge bucket-sort and heap reasoning before chat-moderation top-offender ranking questions.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given an integer array nums and integer k, return the k most frequent elements. You may return the answer in any order.

Constraints

  • 1 <= nums.length <= 10^5
  • k is between 1 and the number of unique elements
  • Solution must be better than O(n log n)

Examples

Example 1

Input
nums=[1,1,1,2,2,3], k=2
Output
[1,2]

Example 2

Input
nums=[1], k=1
Output
[1]

Approaches

1. Sort by frequency

Count, sort entries by count desc, slice first k.

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

Count, then place each element into bucket[freq]. Walk buckets from highest down and collect first k. Linear time.

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 [n,f] of c) buckets[f].push(n);
  const out = [];
  for (let f = buckets.length-1; f >= 0 && out.length < k; f--)
    for (const n of buckets[f]) { out.push(n); if (out.length === k) break; }
  return out;
}

Tradeoff:

Activision-specific tips

Activision likes when you hit O(n) with bucket sort and explain why log-n isn't strictly needed — same trick they reuse when ranking chat-moderation top offenders per match.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Top K Frequent Elements and other Activision interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →