Home  Dsa   Min and max ...

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:


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:


Comparison Table

FeatureJavaPython
Min-HeapPriorityQueue<Integer>()heapq
Max-HeapPriorityQueue<>(Collections.reverseOrder())heapq + negative values
Insertadd() → O(log n)heappush() → O(log n)
Remove toppoll() → O(log n)heappop() → O(log n)
Peek toppeek() → O(1)heap[0] → O(1)

Published on: Oct 11, 2025, 11:42 PM  
 

Comments

Add your comment