Skip to main content

10. Top K Frequent Elements

mediumAsked at Adyen

Given an array, return the k most frequent elements.

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.

Constraints

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

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 then sort entries descending.

Time
O(n log n)
Space
O(n)
const f = new Map();
for (const x of nums) f.set(x, (f.get(x) || 0) + 1);
return [...f.entries()].sort((a,b) => b[1] - a[1]).slice(0,k).map(e => e[0]);

Tradeoff:

2. Bucket sort by frequency

Place each value in a bucket indexed by its frequency, then sweep from the top.

Time
O(n)
Space
O(n)
function topKFrequent(nums, k) {
  const f = new Map();
  for (const x of nums) f.set(x, (f.get(x) || 0) + 1);
  const buckets = Array.from({length: nums.length + 1}, () => []);
  for (const [v, c] of f) buckets[c].push(v);
  const out = [];
  for (let i = buckets.length - 1; i >= 0 && out.length < k; i--) {
    for (const v of buckets[i]) if (out.length < k) out.push(v);
  }
  return out;
}

Tradeoff:

Adyen-specific tips

Adyen frames this as a top-merchants-by-volume problem — they prefer the bucket-sort variant because routing tables prioritize sub-linear scans over heap maintenance.

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

Practice these live with InterviewChamp.AI →