Skip to main content

21. Top K Frequent Elements

mediumAsked at Roblox

Return the k most frequent values from an array — Roblox uses this pattern to surface trending game items, rank popular avatar accessories, and identify the most-crashed experiences from telemetry event streams.

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 algorithm must be better than O(n log n) time complexity.

Constraints

  • 1 <= nums.length <= 10^5
  • k is in the range [1, the number of unique elements in the array]
  • It is guaranteed that the answer is unique

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. Brute force — sort by frequency

Count frequencies with a Map, then sort the unique elements by count descending and slice the top k. O(n log n) due to sort.

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(([num]) => num);
}

Tradeoff:

2. Optimal — bucket sort

After counting frequencies, use the frequency as an index into a bucket array of length n+1. Iterate buckets from high to low, collecting elements until k are gathered. O(n) overall.

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 [num, count] of freq) buckets[count].push(num);

  const result = [];
  for (let i = buckets.length - 1; i >= 0 && result.length < k; i--) {
    result.push(...buckets[i]);
  }
  return result.slice(0, k);
}

Tradeoff:

Roblox-specific tips

Roblox interviewers appreciate bucket sort here because it reflects the kind of frequency-domain thinking used in analytics pipelines. They'll also ask about the min-heap approach (O(n log k) — better when k << n and you're streaming data). Know all three, and be ready to discuss when each wins: sort for simplicity, heap for streaming, bucket for bounded-frequency batch jobs.

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 Roblox interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →