Top K Elements (Heap)

The definitive optimization technique. Use to find K largest/smallest items without doing a full O(N log N) array sort.

Recognition

  • Find the K largest/smallest/most frequent items.
  • A full sort is unnecessary if only the boundary matters.

When not to use it

Do not force this pattern when the input is unordered and hashing is enough.

Avoid coding the template before naming the invariant you need to preserve.

Logic template

Python

import heapq

def top_k(nums, k):
    # Min-heap to keep track of the largest K elements
    min_heap = []
    for num in nums:
        heapq.heappush(min_heap, num)
        if len(min_heap) > k:
            heapq.heappop(min_heap)
    return min_heap

JavaScript

// Typically uses a priority queue/heap library in JS
function topK(nums, k) {
  // Using a MinPriorityQueue class
  const minHeap = new MinPriorityQueue();
  for (let num of nums) {
    minHeap.enqueue(num);
    if (minHeap.size() > k) {
      minHeap.dequeue();
    }
  }
  return minHeap.toArray().map(x => x.element);
}

Typically better than the obvious O(N^2) approach; verify with the template.

  • Name what stays true after every move.
  • Track the exact condition that lets you discard work safely.

Worked example

Recognition drill

Identify the reusable state and the rule that advances it.

  1. Restate the goal in one sentence.
  2. Name the moving parts and what they represent.
  3. Write the loop invariant before coding.
  4. Trace one failing case that breaks a naive approach.

Result: You can explain when to reach for the pattern and when to abandon it.

Common pitfalls

  • Off-by-one updates on loop bounds.
  • Updating state after comparing instead of before.
  • Confusing “solved once” with pattern mastery.

Related practice problems