Skip to main content

18. Top K Frequent Elements

mediumAsked at Quora

Return the k most frequent elements in an array — Quora's question-ranking system runs this exact top-K pattern to surface the most-viewed topics for a given user cohort in real time.

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 and is guaranteed to be unique.

Constraints

  • 1 <= nums.length <= 10^5
  • k is in the range [1, the number of unique elements in the array]
  • The 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. Sort by frequency

Count frequencies with a hash map, sort entries by count descending, take 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))

After counting frequencies, bucket elements by frequency index (1..n). Scan buckets from n down to collect k elements. Beats sort when k << n.

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 [val, cnt] of freq) buckets[cnt].push(val);
  const result = [];
  for (let i = buckets.length - 1; i >= 1 && result.length < k; i--) {
    for (const v of buckets[i]) {
      result.push(v);
      if (result.length === k) break;
    }
  }
  return result;
}

Tradeoff:

Quora-specific tips

Quora probes whether you spot the bucket-sort O(n) shortcut — frequency values are bounded by array length, making sort unnecessary. They care about this optimisation because their topic-ranking pipeline runs on millions of questions per second.

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

Practice these live with InterviewChamp.AI →