126. Complex Data Structures with heapq
1. Basic Min-Heap Usage
import heapq
heap = []
heapq.heappush(heap, 20)
heapq.heappush(heap, 5)
heapq.heappush(heap, 15)
print(heap) # Output: [5, 20, 15]
print(heapq.heappop(heap)) # Output: 5
print(heap) # Output: [15, 20]2. Max-Heap Simulation with Negatives
import heapq
max_heap = []
heapq.heappush(max_heap, -20)
heapq.heappush(max_heap, -5)
heapq.heappush(max_heap, -15)
print([-item for item in max_heap]) # Output: [20, 5, 15]
print(-heapq.heappop(max_heap)) # Output: 20
print([-item for item in max_heap]) # Output: [15, 5]3. Priority Queue with Custom Objects
4. Heapq for Sorting
5. Heapq with heapreplace to Replace Minimum Element
heapreplace to Replace Minimum Element6. Efficient Merging of Multiple Sorted Lists
7. Find the N Largest Elements in a List
8. Find the N Smallest Elements in a List
9. Custom Priority Queue with Tuple and Custom Comparator
10. Kth Smallest Element in a Stream
Last updated