Skip to main content

23. Top K Frequent Elements

mediumAsked at Expedia

Return the k most frequent elements — Expedia's search-ranking pipeline uses the same frequency-heap pattern to surface the top-k destinations by booking volume without sorting the full catalog.

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

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 with a hash map, then sort entries by frequency descending and take the first k.

Time
O(n log 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);

  return [...freq.entries()]
    .sort((a, b) => b[1] - a[1])
    .slice(0, k)
    .map(e => e[0]);
}

Tradeoff:

2. Bucket sort (O(n))

Frequency can range from 1 to n, so create n+1 buckets indexed by frequency. Fill buckets, then read from highest frequency down to collect k elements.

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 = new Array(nums.length + 1).fill(null).map(() => []);
  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:

Expedia-specific tips

Expedia search interviewers expect you to reach for the bucket sort path and articulate why O(n) beats O(n log n) here. Tie it back: 'In a destination-ranking pipeline running millions of queries per day, shaving a log factor off the hot path matters.' That framing lands well with their infra-aware interviewers.

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

Practice these live with InterviewChamp.AI →