Skip to content

Top K Frequent Elements

Return the k values that appear most often: count them in a map, then keep the k best in a min-heap.

MediumHeaps and Top K
Solve on LeetCode

The problem

You get an integer array nums and an integer k. Return the k values that appear most often, in any order. You can assume the answer is unique, so there is never a tie for the last of the k places.

Input nums = [4, 1, 4, 6, 1, 4, 9], k = 2

Output [4, 1]

4 appears three times and 1 twice, while 6 and 9 appear only once.

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

Output [0]

0 appears three times, more than any other value.

Key constraint: Up to 100,000 numbers, and the follow-up asks for something faster than O(n log n).

How to spot the pattern

  • You need the top k items by some score, here how often they appear.
  • Counting is easy with a hash map; the real work is picking the k best counts without sorting them all.

The idea

First count how often each value appears with a hash map. Now you need the k values with the biggest counts, which is a top-k question: keep a min-heap of at most k (count, value) pairs, and whenever it grows past k, pop the pair with the smallest count. The pairs left in the heap belong to the k most frequent values.

Brute force: Count the values, then sort all distinct values by count and take the first k, which takes O(n log n) time in the worst case.

Step by step

  1. 1Count each value's occurrences in a hash map.
  2. 2For each (value, count) pair, push it onto a min-heap ordered by count.
  3. 3If the heap holds more than k pairs, pop the one with the smallest count.
  4. 4Return the values of the pairs left in the heap.

See the pattern move

The heaps and top k pattern on a small example. Step through it, or press play.

Code

import heapq
from collections import Counter


class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        counts = Counter(nums)
        heap = []  # min-heap of (count, value), at most k pairs
        for value, count in counts.items():
            heapq.heappush(heap, (count, value))
            if len(heap) > k:
                heapq.heappop(heap)  # drop the least frequent
        return [value for _, value in heap]

Complexity

Time

O(n log k)

Space

O(n)

Counting is O(n), and each of the at most n distinct values passes through a heap of at most k + 1 pairs; the map can hold n entries.

Watch out for

  • Ordering the heap by value instead of by count.
  • Returning the counts instead of the values.
  • Sorting the whole map by count, which works but is O(n log n) and misses the point of the follow-up.

Follow-up questions

Can you do it in O(n)?

Bucket sort by count: make buckets where bucket c holds the values that appear exactly c times (a count is at most n), then walk the buckets from n down to 1 until you have collected k values.

What if the numbers arrive as a stream that is too big to store?

Exact answers need a count for every distinct value. If memory is tight, keep approximate counts with a sketch (such as Count-Min Sketch) and a small heap of the current top candidates.

In Hinglish

Pehle map mein har number ki ginti karo. Phir count ke hisaab se size k ka min-heap rakho; jo sabse kam baar aaya use nikaalte jao.

Related problems