Skip to main content

25. Top K Frequent Elements

mediumAsked at Lyft

Return the k most frequent elements — Lyft applies the same bucket-frequency pattern to surface the top-k pickup hotspots across a metro area so dispatchers can pre-position drivers before demand spikes.

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, the number of unique elements in nums]
  • It is guaranteed that the answer is unique
  • -10^4 <= nums[i] <= 10^4

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. Heap (min-heap of size k)

Count frequencies with a hash map. Maintain a min-heap of size k over (frequency, element) pairs. When the heap exceeds size k, pop the minimum. The heap holds the top-k.

Time
O(n log k)
Space
O(n + k)
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 (O(n))

Count frequencies, then place elements in bucket[frequency]. Scan buckets from high to low, collecting elements until k are gathered. Beats any comparison-based sort.

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 = Array.from({ length: nums.length + 1 }, () => []);
  for (const [num, count] of freq) buckets[count].push(num);

  const result = [];
  for (let i = buckets.length - 1; i >= 0 && result.length < k; i--) {
    result.push(...buckets[i]);
  }
  return result.slice(0, k);
}

Tradeoff:

Lyft-specific tips

Lyft almost always follows up with 'can you do better than O(n log n)?' — that's your cue to pivot to bucket sort. The key insight: frequencies are bounded by n, so buckets of size n+1 cover all cases. Mention that Lyft's real system uses a count-min sketch for approximate top-k over unbounded streams, but exact bucket sort is right for the interview.

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

Practice these live with InterviewChamp.AI →