AAlgoLoopSpaced repetition for LeetCode
MEDIUMHeap / Priority QueueLeetCode ↗

Top K Frequent Elements

The key idea

Count how often each value appears, then you only need the k values with the largest counts. A size-k min-heap keyed by frequency keeps just those k while discarding everything smaller, and bucketing by frequency removes the sort entirely for an O(n) pass.

Problem

You are given an integer array nums and an integer k. Return the k most frequent elements — the k values that appear the most times in nums. You may return the answer in any order.

The count of an element is how many times it occurs in nums. The answer is guaranteed to be unique, so there is no ambiguity about which k values to return.

Constraints

Examples

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

Complexity

Time: O(n log k) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Heap / Priority Queue problems