🧩 Patterns
Priority Queue / Heap
Get the min or max in O(log n) — and how max-heap differs per language
A heap gives you the smallest (or largest) element in O(log n). The tricky part: Python's heapq is min-heap only. For max-heap you negate values. Java and C++ have both.
Language:
Python
Loading...
All languages — Min heap
JavaScript
// JavaScript has no built-in heap.
// In interviews use a sorted array (ok for small n)
// or implement a simple MinHeap:
class MinHeap {
constructor() { this.data = []; }
push(val) {
this.data.push(val);
this.data.sort((a, b) => a - b); // naive — O(n log n)
}
pop() { return this.data.shift(); }
peek() { return this.data[0]; }
get size() { return this.data.length; }
}
const h = new MinHeap();
h.push(5); h.push(1); h.push(3);
console.log(h.pop()); // 1TypeScript
// Same as JS — no built-in heap.
class MinHeap {
private data: number[] = [];
push(val: number) {
this.data.push(val);
this.data.sort((a, b) => a - b);
}
pop(): number | undefined { return this.data.shift(); }
peek(): number | undefined { return this.data[0]; }
get size(): number { return this.data.length; }
}Java
import java.util.PriorityQueue;
// Min heap (default):
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
minHeap.offer(5);
minHeap.offer(1);
minHeap.offer(3);
minHeap.poll(); // 1 ← removes min
minHeap.peek(); // next min, no remove
minHeap.size();Go
import "container/heap"
// Go requires implementing the heap.Interface:
type MinHeap []int
func (h MinHeap) Len() int { return len(h) }
func (h MinHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *MinHeap) Push(x any) { *h = append(*h, x.(int)) }
func (h *MinHeap) Pop() any {
old := *h; n := len(old)
x := old[n-1]; *h = old[:n-1]; return x
}
h := &MinHeap{5, 1, 3}
heap.Init(h)
heap.Push(h, 2)
fmt.Println(heap.Pop(h)) // 1C++
#include <queue>
// Min heap:
priority_queue<int, vector<int>, greater<int>> minHeap;
minHeap.push(5);
minHeap.push(1);
minHeap.push(3);
minHeap.top(); // 1 ← peek
minHeap.pop(); // removes min
minHeap.size();