AlgoInsight

DSA problem

Top K Frequent Elements

MediumTop K ElementsPattern: Top K Elementstop75FreeAmazonMicrosoftGoogleMetaApple

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 — there is no ambiguity in which k values tie for the cutoff frequency.

A correct but slow approach builds a frequency map, sorts the (value, frequency) pairs in descending order of frequency, and slices off the first k. That costs O(n log n) time and is unnecessarily expensive when k is small compared to n.

The canonical heap-based solution avoids sorting the entire frequency table. Count frequencies with a hash map in O(n). Then push entries into a min-heap keyed by frequency of size k: whenever the heap grows beyond k items, pop the least frequent. After processing every distinct value, the heap holds exactly the k most frequent. This runs in O(n log k), which is strictly better when k is small.

An even faster alternative is bucket sort by frequency. Because every frequency is in the range [1, n], we can create n + 1 buckets and place each value into the bucket indexed by its frequency. Reading buckets from high to low and collecting the first k values gives an O(n) solution. The follow-up in the problem statement explicitly asks for an algorithm better than O(n log n), and bucket sort hits the linear-time floor. The heap solution shown below is the most widely used pattern, with bucket sort noted as an alternative.

Examples

Example 1
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Explanation: The frequency map is {1:3, 2:2, 3:1}. The two most frequent values are 1 (three times) and 2 (two times).
Example 2
Input: nums = [1], k = 1
Output: [1]
Explanation: There is only one distinct value, so it is trivially the most frequent.
Example 3
Input: nums = [4,4,4,5,5,6,6,7], k = 2
Output: [4,5]
Explanation: Frequencies are {4:3, 5:2, 6:2, 7:1}. The top two by frequency are 4 and 5 (tie broken by uniqueness guarantee).

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

heappriority-queuehash-tablebucket-sorttop-k

Browse all DSA problems