Skip to main content

13. Top K Frequent Elements

mediumAsked at Rappi

Return the k most frequent elements in an array — Rappi frames this as ranking the top-k busiest pickup zones from a stream of dispatch events.

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

Problem

Given an integer array nums and an integer k, return the k most frequent elements. The answer may be returned 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 count

Tally counts, sort unique keys by count, take first k.

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

Tradeoff:

2. Bucket sort by frequency

Index frequencies into buckets[0..n], then walk buckets from high to low collecting until k.

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

Tradeoff:

Rappi-specific tips

Rappi will push for the O(n) bucket-sort answer — their hot-zone ranker must run faster than log-linear when the event stream spikes during meal-rush hours.

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

Practice these live with InterviewChamp.AI →