Heaps & Priority Queues
1 / 8
1
/ \
3 2
/ \
7 4
Array: [1, 3, 2, 7, 4]
| Operation | Time |
|---|---|
| Peek | O(1) |
| Push | O(log n) |
| Pop | O(log n) |
| Build | O(n) |
import heapq
nums = [3, 1, 4]
heapq.heapify(nums)
heapq.heappush(nums, 2)
min_val = heapq.heappop(nums)
# Max-heap: negate values
heapq.heappush(heap, -x)
max_val = -heapq.heappop(heap)
Keep min-heap of size k:
heap = nums[:k]
heapq.heapify(heap)
for num in nums[k:]:
if num > heap[0]:
heapq.heapreplace(heap, num)
return heap[0] # kth largest
Time: O(n log k)
counts = Counter(nums)
heap = []
for num, freq in counts.items():
heapq.heappush(heap, (freq, num))
if len(heap) > k:
heapq.heappop(heap)
heap = [(lst.val, i, lst) for i, lst in enumerate(lists) if lst]
heapq.heapify(heap)
while heap:
val, i, node = heapq.heappop(heap)
# append node
if node.next:
heapq.heappush(heap, (node.next.val, i, node.next))