A heap is for repeatedly asking “what is the smallest priority right now?” Build is O(n), peek is O(1), push/pop are O(log n). It does not keep the whole collection sorted.
| operation | Python | Go | TypeScript | C++ |
|---|---|---|---|---|
| create | import heapq |
type IntHeap []int |
// no built-in heap |
priority_queue<int, vector<int>, greater<int>> pq; |
| build from items avg O(n) |
h = nums[:] |
h := IntHeap(nums) |
const h = MinHeap.from(nums, (a, b) => a - b) |
priority_queue<int, vector<int>, greater<int>> pq(greater<int>{}, nums); |
| push avg O(log n) |
heapq.heappush(h, x) |
heap.Push(&h, x) |
h.push(x) |
pq.push(x); |
| peek min avg O(1) |
h[0] |
h[0] |
h.peek() |
pq.top() |
| pop min avg O(log n) |
x = heapq.heappop(h) |
x := heap.Pop(&h).(int) |
const x = h.pop() |
int x = pq.top(); |
| replace root avg O(log n) |
x = heapq.heapreplace(h, y) |
h[0] = y |
const x = h.replace(y) |
pq.pop(); |
| operation | Python | Go | TypeScript | C++ |
|---|---|---|---|---|
| max-heap same costs |
heapq.heappush(h, -x) |
// reverse Less |
const h = new MinHeap<number>((a, b) => b - a) |
priority_queue<int> pq; |
| priority item avg O(log n) |
heapq.heappush(h, (pri, seq, item)) |
type Item struct { pri, seq int; val string } |
type Item = { pri: number; seq: number; val: string } |
using T = tuple<int, int, string>; |
| push then pop avg O(log n) |
x = heapq.heappushpop(h, y) |
heap.Push(&h, y) |
h.push(y) |
pq.push(y); |
| pattern | Python | Go | TypeScript | C++ |
|---|---|---|---|---|
| top-K largest avg O(n log k), space O(k) |
def top_k(nums, k): |
// keep min-heap size k |
if (h.size() < k) h.push(x) |
if (pq.size() < k) pq.push(x); |
| running median add O(log n), median O(1) |
low, high = [], [] |
// low: max-heap, high: min-heap |
const low = new MinHeap<number>((a, b) => b - a) |
priority_queue<int> low; |
| Python | Go | TypeScript | C++ |
|---|---|---|---|
|
|
|
|
Official docs: https://docs.python.org/3/library/heapq.html, https://pkg.go.dev/container/heap, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort, https://en.cppreference.com/w/cpp/container/priority_queue.