Intermediate·Concept·2 min read

Heaps and priority queue in Java

Practice this question

Important class

java
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());

Problems to practice

  • Kth largest element
  • Top K frequent elements
  • Merge K sorted lists
  • Find median in stream

Example: min heap

java
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.offer(5);
pq.offer(3);
pq.offer(9);
System.out.println(pq.peek()); // 3

Time and space complexity

  • Insert: O(log n)
  • Peek: O(1)
  • Remove min: O(log n)

Adapted from 15_DSA_JAVA.md · “8. Heaps and priority queue in Java”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.