Skip to main content

24. Top K Frequent Elements

mediumAsked at Mercury

Return the k most frequent elements from an integer array.

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; ties may be broken arbitrarily.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= k <= number of distinct values

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 count

Build a count map, sort entries by count desc, take first k.

Time
O(n log n)
Space
O(n)
const c=new Map();
for(const x of nums) c.set(x,(c.get(x)||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

Counts cannot exceed n, so put each value into bucket[count]; walk buckets from high to low, pulling k values. Linear time.

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

Tradeoff:

Mercury-specific tips

Mercury asks Top-K in the context of multi-account aggregation dashboards — finding the top-k merchants by spend across an org's 30 sub-accounts shows up as a real interview prompt verbatim.

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

Practice these live with InterviewChamp.AI →