Heaps and priority queue in Java
Practice this questionWANT TO UNDERSTAND THE CONCEPT FIRST?Learn Heaps and priority queue in Java
Important class
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
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.offer(5);
pq.offer(3);
pq.offer(9);
System.out.println(pq.peek()); // 3Time 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.