Skip to main content

347. Top K Frequent Elements

mediumAsked at LinkedIn

Return the k most frequent elements from an array — this is the algorithm behind LinkedIn's 'People You May Know' ranking and trending job suggestion surfaces, where you need the top-K signals from a frequency count without sorting the entire dataset.

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. It is guaranteed that the answer is unique.

Constraints

  • 1 <= nums.length <= 10^5
  • k is in the range [1, number of unique elements in nums]
  • The answer is unique

Examples

Example 1

Input
nums = [1,1,1,2,2,3], k = 2
Output
[1,2]

Explanation: 1 appears 3 times, 2 appears 2 times — these are the top 2.

Example 2

Input
nums = [1], k = 1
Output
[1]

Approaches

1. Sort by frequency

Build a frequency map, then sort the unique elements by count descending and return the first k. Simple but O(n log n) — fails the 'better than O(n log n)' follow-up.

Time
O(n log n)
Space
O(n)
function topKFrequentSort(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(([val]) => val);
}

Tradeoff:

2. Bucket sort — O(n) optimal

Create an array of n+1 buckets indexed by frequency. Drop each element into its frequency bucket. Scan buckets from highest to lowest, collecting results until k elements are gathered. True O(n) with no heap overhead.

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);
  // buckets[i] = all elements with frequency i
  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 >= 0 && result.length < k; i--) {
    for (const val of buckets[i]) {
      result.push(val);
      if (result.length === k) break;
    }
  }
  return result;
}

Tradeoff:

LinkedIn-specific tips

LinkedIn's follow-up is almost always 'can you do better than O(n log n)?' — the bucket-sort answer is the expected response, not a min-heap (which is O(n log k), better than sort but not O(n)). State the bucket-sort approach directly: 'Since frequencies are bounded by n, I can allocate n+1 buckets and avoid any comparison-based sort entirely.' If they ask about a stream where n is unbounded, switch to a min-heap of size k: O(n log k) and still better than full sort.

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

Practice these live with InterviewChamp.AI →