Skip to main content

21. Top K Frequent Elements

mediumAsked at N26

Given an integer array, return the k most frequent elements. N26 frames it as picking the top-k merchant categories per customer for category-spend insights.

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

Problem

Given an integer array nums and an integer k, return the k most frequent elements in any order. You must aim for better than O(n log n).

Constraints

  • 1 <= nums.length <= 10^5
  • k is in the range [1, number of unique elements]
  • Answer is guaranteed to be 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. Count then sort

Hash-count, then sort all unique keys by frequency and take the top k.

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

Tradeoff:

2. Bucket sort by frequency

Frequencies are bounded by n, so put each unique element into a bucket indexed by its count. Scan buckets from high to low until k items are collected.

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

Tradeoff:

N26-specific tips

N26 likes when you connect bucket sort to their spend-insights pipeline, where merchant-category counts are pre-aggregated by month and the dashboard only ever needs the top 5.

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

Practice these live with InterviewChamp.AI →