min and max heap in Java and Python
Both Java and Python support min-heap and max-heap, but the way you do it is slightly different in each language. Let me explain clearly.
1️⃣ Java
Java has the PriorityQueue class in java.util:
Min-Heap (default)
import java.util.PriorityQueue;
public class MinHeapExample {
public static void main(String[] args) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>(); // default = min-heap
minHeap.add(8);
minHeap.add(5);
minHeap.add(10);
minHeap.add(3);
while (!minHeap.isEmpty()) {
System.out.println(minHeap.poll()); // always returns the smallest element
}
}
}
Output:
3
5
8
10
Max-Heap
import java.util.PriorityQueue;
import java.util.Collections;
public class MaxHeapExample {
public static void main(String[] args) {
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
maxHeap.add(8);
maxHeap.add(5);
maxHeap.add(10);
maxHeap.add(3);
while (!maxHeap.isEmpty()) {
System.out.println(maxHeap.poll()); // always returns the largest element
}
}
}
Output:
10
8
5
3
✅ Key point: In Java,
PriorityQueuedefaults to min-heap, useCollections.reverseOrder()for max-heap.
2️⃣ Python
Python has the heapq module, which is min-heap by default:
Min-Heap
import heapq
heap = []
for num in [8,5,10,3]:
heapq.heappush(heap, num) # add element
while heap:
print(heapq.heappop(heap)) # always smallest element
Output:
3
5
8
10
Max-Heap
Python doesn’t have a built-in max-heap, but you can simulate it using negative numbers:
import heapq
heap = []
for num in [8,5,10,3]:
heapq.heappush(heap, -num) # invert the number
while heap:
print(-heapq.heappop(heap)) # invert back
Output:
10
8
5
3
✅ Trick: Python’s
heapqis always min-heap, use negatives for max-heap.
🔹 Summary
| Language | Min-Heap | Max-Heap |
|---|---|---|
| Java | PriorityQueue<>() | PriorityQueue<>(Collections.reverseOrder()) |
| Python | heapq (default) | heapq + negative numbers |
Published on: Oct 08, 2025, 05:22 AM