Skip to main content

DSAPath16 mincore

heapq Patterns

heapq patterns use Python's min-heap for top-k selection, Dijkstra, schedulers, merging streams, and best-next-item problems.

DifficultyCore
TierTier 2
ModulePython Practice
LanguagesPython

Why This Matters

heapq is Python's standard priority queue tool. It is a min-heap, which makes the smallest priority cheap to retrieve without sorting all candidates every time.

Core Idea

Use heapq when the algorithm repeatedly needs the best next item.

MethodRole
heapifyturn a list into a heap in linear time
heappushadd a candidate
heappopremove the smallest candidate
heappushpoppush and pop in one combined operation
nlargest / nsmallestconvenience top-k helpers

Non-Example or Failure Mode

heapq does not support decrease-key directly. Dijkstra implementations usually push a new pair and ignore a stale entry when it comes out of the heap.

Runnable Drill

heapq top-k and Dijkstra drill

Output will appear here.

Common Mistakes

MistakeCorrection
Forgetting that heapq is a min-heap.Negate priorities or invert comparison data for max behavior.
Sorting the full input for small top-k.Keep a size-k heap.
Failing to skip a stale entry in Dijkstra.Compare popped distance with the current best distance.
Putting unorderable payloads in heap tuples after equal priorities.Add a tie-breaker such as an incrementing counter.

Diagnostic Questions

Question typeQuestionAnswer signal
DefinitionWhat does heapq expose?A min-heap over a Python list.
Example / non-exampleDoes heapq have direct decrease-key?No. Push a new priority and skip stale entries.
ComputationWhat is the push/pop cost?O(log n).
TransferWhy does Dijkstra use a heap?It repeatedly needs the node with smallest tentative distance.

Exercises

Beginner:

  • Use heapify and heappop to sort a small list by repeated pops.
  • Keep the three largest values from a stream.
  • Simulate a task scheduler with (priority, task) pairs.

Intermediate:

  • Implement Dijkstra with stale-entry skipping.
  • Add a tie-breaker counter to a priority queue.

Challenge:

  • Compare full sorting vs heap top-k for k << n.

References