layersHeap / Priority Queue

Heap / Priority Queue: when to spot it, explain it, and practice it

Heap problems are about maintaining a moving frontier. If you keep asking for the next best, next smallest, or current top-k choice, a priority queue often gives you the right balance of speed and clarity.

Pattern coverage

40+

Best first move

Decide whether you need a min heap, max heap, or two heaps.

Common failure point

Using the wrong heap polarity and then writing inverted logic everywhere.

When this pattern should come to mind

You repeatedly need the current smallest, largest, or earliest finishing item.
The answer depends on maintaining only the best k candidates.
A sorted array would work but would be too expensive after every insertion.

Checklist before you code

Decide whether you need a min heap, max heap, or two heaps.
Push only the state required by later comparisons.
If the heap should stay size k, enforce it immediately after each push.
Be clear about whether stale entries are allowed and how to discard them.

The solving flow that works well in interviews

1

Define what the heap top represents in one sentence.

2

Push new candidates as soon as they become eligible.

3

Pop only when the top no longer belongs in the frontier or the size is too large.

4

If two heaps are used, rebalance after every insertion or removal.

5

Convert the final heap state back into the required answer format.

Common variants

Top-k maintenance

Keep the best k candidates seen so far.

Merge frontier

Pick the next smallest head across multiple sorted lists or streams.

Dual-heap balance

Use two heaps when you need both lower-half and upper-half information.

Template preview

PythonPublic preview
import heapq

heap = []
heapq.heappush(heap, value)
smallest = heapq.heappop(heap)

# max heap in Python
heapq.heappush(heap, -value)
largest = -heapq.heappop(heap)

A more useful problem ladder for practice

This is not a random list. It is ordered to help candidates build recognition first, add key variants next, and then increase pressure with harder cases.

High-frequency mistakes

warning

Using the wrong heap polarity and then writing inverted logic everywhere.

warning

Forgetting to cap the heap size in top-k problems.

warning

Not cleaning stale entries when the heap stores delayed state.

warning

Comparing the wrong field when tuples contain multiple priorities.

Recommended practice path

1

Start with kth largest and top-k frequency.

2

Then do merge-k-lists and interval scheduling style heaps.

3

Add two-heap median problems after that.

4

Finish with harder frontier-expansion questions such as smallest range or meeting rooms.

Heap / Priority Queue Pattern Guide | LeetCode Interview Prep - Interview AiBox