Browse curriculum

Heap / Priority Queue

Heap / Priority Queue Interview Questions: 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. Below are the heap / priority queue interview questions from LeetCode, each with a step-by-step visual solution.

16

Interactive problems

2

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 interview questions: 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)
Smallest Number in Infinite SetMediumΩ(1)Θ(log n)O(log n)O(n)
Maximum Subsequence ScoreMediumΩ(n log n)Θ(n log n)O(n log n)O(n)
Total Cost to Hire K WorkersMediumΩ((k + c) log c)Θ((k + c) log c)O((k + c) log c)O(c)
Kth Largest Element in a StreamEasyΩ(log k)Θ(log k)O(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)
Design TwitterMediumΩ(1)Θ(f + 10 log f)O(f + 10 log f)O(tweets + follows)
Kth Smallest Element in a Sorted MatrixMediumΩ(k log min(n, k))Θ(k log min(n, k))O(k log min(n, k))O(min(n, k))
Find Median from Data StreamHardΩ(log n)Θ(log n)O(log n)O(n)
Last Stone WeightEasyΩ(n)Θ(n log n)O(n log n)O(n)
Network Delay TimeMediumΩ(E log E)Θ(E log E)O(E log E)O(V + E)
Min Cost to Connect All PointsMediumΩ(n² log n)Θ(n² log n)O(n² log n)O(n²)
Swim in Rising WaterHardΩ(n² log n)Θ(n² log n)O(n² 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 18 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.

Directory

Every other coding interview pattern