Coding problem · Medium · Arrays & Hashing

Top K Frequent Elements

Medium Algorithms & data structures Most askedSeen at Amazon, Meta, Oracle, Yelp

Given an integer array nums and an integer k, return the k most frequent elements, in any order. The answer is guaranteed to be unique.

Example 1

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

Example 2

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

Constraints

  • 1 <= k <= number of distinct values

Hints

Hint 1

Count frequencies first.

Hint 2

Bucket sort: index = frequency, so walking buckets from high to low gives the answer in O(n).

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n) with buckets · Space O(n)

Count with a hash map, then avoid a full sort: put each value into buckets[count] and walk buckets from the highest frequency down until you have k values — O(n). A min-heap of size k (O(n log k)) is the other standard answer and is worth mentioning.

Reference solution

function topKFrequent(nums, k) {
  const count = new Map();
  for (const x of nums) count.set(x, (count.get(x) ?? 0) + 1);
  const buckets = Array.from({ length: nums.length + 1 }, () => []);
  for (const [x, c] of count) buckets[c].push(x);
  const out = [];
  for (let c = buckets.length - 1; c > 0 && out.length < k; c--) out.push(...buckets[c]);
  return out.slice(0, k);
}