Home  Dsa   Min and max ...

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, PriorityQueue defaults to min-heap, use Collections.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 heapq is always min-heap, use negatives for max-heap.


🔹 Summary

LanguageMin-HeapMax-Heap
JavaPriorityQueue<>()PriorityQueue<>(Collections.reverseOrder())
Pythonheapq (default)heapq + negative numbers

Published on: Oct 08, 2025, 05:22 AM  
 

Comments

Add your comment