Heaps
A heap (or Priority Queue) is a specialized tree-based data structure that satisfies the heap property, allowing for efficient retrieval of the minimum or maximum element.
This pattern uses a min-heap of size K to efficiently find the Kth largest/smallest element or the top K frequent/largest/smallest elements in a collection.
Example Problems:
Kth Largest Element in an ArrayTop K Frequent ElementsK Closest Points to Origin
Solution Spotlight: Kth Largest Element in an Array
This solution maintains a min-heap of size
k. For each number, it adds it to the heap. If the heap grows larger than k, the smallest element is removed. This ensures the heap always holds the top k largest elements seen so far.KthLargestElementinanArray.java
Loading code syntax...