Heap / Priority Queue Cheat Sheet
Quick reference for coding interviews. Bookmark this page!
What is Heap / Priority Queue?
Maintain priority with heap-based data structures.
Trigger Words
When you see these in a problem, think Heap / Priority Queue:
Template Code
import heapq
class KthLargest:
def __init__(self, k: int, nums: List[int]):
self.k = k
self.heap = nums
heapq.heapify(self.heap)
while len(self.heap) > k:
heapq.heappop(self.heap)
def add(self, val: int) -> int:
heapq.heappush(self.heap, val)
if len(self.heap) > self.k:
heapq.heappop(self.heap)
return self.heap[0]
Complexity
| Typical Time | O(log k) per add |
|---|---|
| Typical Space | O(k) |
Common Variations
- Basic Heap / Priority Queue
- Heap / Priority Queue with constraints
- Optimized Heap / Priority Queue
Practice Problems
See all Heap / Priority Queue problems →Practice Heap / Priority Queue
Learn to recognize patterns instantly with interactive MCQs.
Download LeetEye Free