min and max heap in Java and Python
Let’s go through min-heap and max-heap in both Java and Python with clear examples and key points.
1️⃣ Java
Min-Heap
import java.util.PriorityQueue;
public class MinHeapExample {
public static void main(String[] args) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>(); // min-heap by default
minHeap.add(5);
minHeap.add(1);
minHeap.add(3);
System.out.println("Min element: " + minHeap.peek()); // 1
while (!minHeap.isEmpty()) {
System.out.print(minHeap.poll() + " "); // 1 3 5
}
}
}
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(5);
maxHeap.add(1);
maxHeap.add(3);
System.out.println("Max element: " + maxHeap.peek()); // 5
while (!maxHeap.isEmpty()) {
System.out.print(maxHeap.poll() + " "); // 5 3 1
}
}
}
✅ Key points in Java:
PriorityQueue= min-heap by default.- Use
Collections.reverseOrder()for max-heap. - Operations:
add()→ O(log n),poll()→ O(log n),peek()→ O(1).
2️⃣ Python
Min-Heap
import heapq
min_heap = []
heapq.heappush(min_heap, 5)
heapq.heappush(min_heap, 1)
heapq.heappush(min_heap, 3)
print("Min element:", min_heap[0]) # 1
while min_heap:
print(heapq.heappop(min_heap), end=" ") # 1 3 5
Max-Heap
Python’s heapq is min-heap by default, but we can simulate a max-heap by storing negative values:
import heapq
max_heap = []
heapq.heappush(max_heap, -5)
heapq.heappush(max_heap, -1)
heapq.heappush(max_heap, -3)
print("Max element:", -max_heap[0]) # 5
while max_heap:
print(-heapq.heappop(max_heap), end=" ") # 5 3 1
✅ Key points in Python:
heapqonly provides min-heap.- Max-heap = push negative values.
- Operations:
heappush()→ O(log n),heappop()→ O(log n),heap[0]→ O(1).
Comparison Table
| Feature | Java | Python |
|---|---|---|
| Min-Heap | PriorityQueue<Integer>() | heapq |
| Max-Heap | PriorityQueue<>(Collections.reverseOrder()) | heapq + negative values |
| Insert | add() → O(log n) | heappush() → O(log n) |
| Remove top | poll() → O(log n) | heappop() → O(log n) |
| Peek top | peek() → O(1) | heap[0] → O(1) |
Published on: Oct 11, 2025, 11:42 PM