Intermediate·Concept·2 min read

Heap and priority queue in Python

Practice this question

Built-in heapq

Python
import heapq

heap = [5, 3, 9]
heapq.heapify(heap)
heapq.heappush(heap, 1)
print(heap[0])

Problems to practice

  • Kth largest element
  • Top K frequent elements
  • Merge K sorted lists
  • Median in stream

Interview guidance

heapq gives us a min-heap by default. For max-heap, push negatives.


Adapted from 18_DSA_PYTHON.md · “8. Heap and priority queue in Python”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.