Browse curriculum

Heap / Priority Queue

The Heap / Priority Queue Pattern

A heap keeps the smallest or largest element instantly reachable while allowing insertions and removals in logarithmic time. Keeping a heap of size k gives you the top k of a stream without ever sorting the whole input.

6

Interactive problems

1

Free to open

Recognise

How do you recognise a heap / priority queue problem?

The question says "top k", "k largest", "k closest", "median of a stream", or requires repeatedly taking the current minimum — which is what makes it the engine inside Dijkstra and k-way merges.

Complexity

What is the time complexity of the heap / priority queue pattern?

O(n log k) for a top-k pass against O(n log n) for a full sort. Peeking is O(1); push and pop are O(log n).

Problems

Heap / Priority Queue practice problems

Each problem pairs a worked explanation with an interactive visualizer you step through yourself, plus the implementation in JavaScript, Python, Java and C++.

Complexity

Heap / Priority Queue problems by difficulty and complexity

The difficulty, running time and extra space of every heap / priority queue solution on this page, as each lesson derives them.

LessonDifficultyBestAverageWorstSpace
Heap OverviewEasyΩ(1)Θ(log n)O(log n)O(n)
Kth Largest Element in an ArrayMediumΩ(n)Θ(n log k)O(n log k)O(k)
K Closest Points to OriginMediumΩ(n)Θ(n log k)O(n log k)O(k)
Find K Closest ElementsMediumΩ(n)Θ(n)O(n)O(k)
Merge K Sorted ListsHardΩ(N)Θ(N log k)O(N log k)O(k)
Find Median from Data StreamHardΩ(log n)Θ(log n)O(log n)O(n)
Curriculum

The underlying technique is covered from first principles in the heap / priority queue lesson in the DSA visualizer curriculum. Heap / Priority Queue is one of the 17 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.

Directory

Every other coding interview pattern