← Heap / Priority Queue

Pattern Recognition Drill

#59 — Top K frequent elements

Medium Heaps

The Problem

Given an array of integers and k, return the k most frequent elements.

What approach would you use?

Think about it before scrolling down.

Key Signals

Heap / Priority Queue

Count with Counter, then use min-heap of size k. Push all, pop when size > k. O(n log k).

Alt: Hash Map

Bucket sort by frequency: create buckets[freq] = [elements]. Scan from highest bucket. O(n).

Common Trap

Sorting all elements by frequency is O(n log n). Heap of size k is O(n log k) — better when k << n.

← #58 #60 →