Skip to main content

28. Top K Frequent Elements

mediumAsked at Dropbox

Return the k most frequently occurring integers from an array — Dropbox uses frequency ranking to surface the most-accessed file types in a user's account, driving smart sync-priority decisions.

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^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. Sort by frequency

Count frequencies with a hash map, then sort the unique elements by count 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(([num]) => num);
}

Tradeoff:

2. Bucket sort (linear time)

Frequency can be at most n, so create n+1 buckets indexed by count. Place each element into its frequency bucket. Scan buckets from high to low, collecting elements until k are gathered.

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, count] of freq) {
    buckets[count].push(num);
  }
  const result = [];
  for (let i = buckets.length - 1; i >= 0 && result.length < k; i--) {
    for (const num of buckets[i]) {
      result.push(num);
      if (result.length === k) break;
    }
  }
  return result;
}

Tradeoff:

Dropbox-specific tips

Dropbox interviewers watch for the bucket sort insight — the O(n) bound is achievable because frequencies are bounded by n. If you only know the heap approach (O(n log k)), mention it as a valid middle ground when n is large but k is very small. Also be ready to extend the problem to a stream: 'If elements arrive one at a time, how do you maintain the top-k efficiently?'

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

Practice these live with InterviewChamp.AI →