Data Structures & Algorithms Heaps & Priority Queues
💡
Exercise 102

Heap Basics 10 XP Easy

Ctrl+Enter Run Ctrl+S Save

A Heap (Priority Queue) is a special tree where the smallest (or largest) element is ALWAYS at the top. Perfect when you repeatedly need the min/max! 🏔️

💡 Think of it like this: Imagine an emergency room. Patients aren't served in arrival order — the most critical patient is always treated first. That's a priority queue!

import heapq # Min-heap: smallest always on top heap = [] heapq.heappush(heap, 5) # [5] heapq.heappush(heap, 1) # [1, 5] heapq.heappush(heap, 3) # [1, 5, 3] print(heap[0]) # Peek: 1 (smallest) — O(1) print(heapq.heappop(heap)) # Pop: 1 (removed) — O(log n) print(heapq.heappop(heap)) # Pop: 3 — O(log n)

Heap operations:

  • 📥 heappush(heap, val) — Insert: O(log n)
  • 📤 heappop(heap) — Remove smallest: O(log n)
  • 👀 heap[0] — Peek at smallest: O(1)
  • 🔄 heapify(list) — Convert list to heap: O(n)
  • 🔄 For max-heap: negate values! Push -val, negate after pop

Classic heap interview problems:

  • 🏆 Top K elements: Use a min-heap of size k
  • 📊 Find median: Two heaps (max-heap for left, min-heap for right)
  • 🔀 Merge K sorted lists: Push first element of each, pop smallest, push next
  • 🗺️ Dijkstra's algorithm: Uses a min-heap for shortest paths
📋 Instructions
Practice heap operations. Push values [4, 1, 7, 3, 8, 5] one at a time. Pop all elements and print them (they'll come out sorted!).
Use heapq.heappush() to add each element, then while heap: print(heapq.heappop(heap)). Elements come out in ascending order.
🧪 Test Cases
Input
result
Expected
[1, 3, 4, 5, 7, 8]
Test case 1
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.