Pattern #28
Heap / Priority Queue
Important interview questions, thinking patterns, Min/Max Heap invariants, Top K size algorithms, two-heaps median finding, and container/heap rules in Go.
Must Solve
15 core questions — solve these first.
- 1.Kth Largest Element in an ArrayMin Heap size K in O(N log K) time or Quickselect in O(N)medium
- 2.Top K Frequent ElementsFrequency HashMap + Min Heap of size K based on countmedium
- 3.K Closest Points to OriginMax Heap size K storing (distance, point)medium
- 4.Find Median from Data StreamTwo Heaps: Max Heap (lower half) + Min Heap (upper half)hard
- 5.Merge K Sorted ListsMin Heap storing head node from each list (O(N log K))hard
- 6.Task SchedulerMax Heap for task frequency + cooldown queuemedium
- 7.Last Stone WeightMax Heap smashing two largest stones repeatedlyeasy
- 8.Kth Largest Element in a StreamMaintain Min Heap of size Keasy
- 9.Meeting Rooms IIMin Heap storing meeting end times to track active roomsmedium
- 10.Reorganize StringMax Heap of character frequencies + previous character holdmedium
- 11.Furthest Building You Can ReachMin Heap of brick jumps, replace smallest jumps with laddersmedium
- 12.Smallest Range Covering Elements from K ListsMin Heap storing current elements across K listshard
- 13.IPOSort projects by capital + Max Heap for available profitshard
- 14.Minimum Cost to Connect SticksMin Heap combining two smallest sticks repeatedly (Greedy)medium
- 15.Total Cost to Hire K WorkersTwo Min Heaps for first & last candidate windowshard
Also Important
10 more questions worth practicing.
- 16.Kth Smallest Element in a Sorted MatrixMin Heap row candidates or Binary Search on rangemedium
- 17.Find K Pairs with Smallest SumsMin Heap storing (sum, i, j) index pairsmedium
- 18.Seat Reservation ManagerMin Heap tracking available seat numbersmedium
- 19.Single-Threaded CPUSort tasks by enqueue time + Min Heap by processing durationmedium
- 20.Process Tasks Using ServersTwo Min Heaps: free servers (weight, index) & busy servers (free_time)medium
- 21.Maximum Performance of a TeamSort by efficiency + Min Heap of speed sum for top K engineershard
- 22.Minimum Number of Refueling StopsMax Heap of available fuel stations passedhard
- 23.Ugly Number IIMin Heap generating numbers multiplied by 2, 3, 5 + HashSetmedium
- 24.Sliding Window MedianTwo Heaps with lazy element deletion or multisethard
- 25.Minimum Cost to Hire K WorkersSort ratio (wage/quality) + Max Heap of qualitieshard
How to Think
- Need smallest item again and again?Min Heap (Peek O(1), Pop O(log N))
- Need largest item again and again?Max Heap (Peek O(1), Pop O(log N))
- Need Top K largest items?Min Heap of size K (O(N log K) time)
- Need Kth largest item?Min Heap of size K (Top is the answer!)
- Need merge K sorted lists?Min Heap storing candidate head nodes
- Need process highest-priority task?Priority Queue (stores (priority, payload))
Go container/heap Interface
Standard Min Heap Implementation in Go
import "container/heap"
type IntHeap []int
func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } // Min Heap (change to > for Max Heap!)
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x interface{}) {
*h = append(*h, x.(int))
}
func (h *IntHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
// Usage:
// h := &IntHeap{}
// heap.Init(h)
// heap.Push(h, 5)
// minVal := heap.Pop(h).(int)👉 Push/Pop: O(log N) | Peek Top: h[0] in O(1) | Init: O(N)
Why Min Heap for K Largest? (Crucial Interview Concept)
To find the K largest values in an array of size N, maintain a Min Heap of size K.
Why Min Heap? Because among the K largest items kept, the smallest element stays at the root (top). When a new element comes along:
heap.Push(h, val)
if h.Len() > K {
heap.Pop(h) // Evicts the smallest element among the top K candidates!
}👉 After processing all N items, the top of the Min Heap is the Kth largest element in O(N log K) time!
Two Heaps Median Pattern
Stores the smaller half of data numbers. Root yields the maximum element of the lower half.
Stores the larger half of data numbers. Root yields the minimum element of the upper half.
Peek Top → O(1) time
Push / Pop → O(log N) time
Top K → Heap size K (O(N log K) time)
Kth Largest → Min Heap size K (Root = answer)
Kth Smallest→ Max Heap size K (Root = answer)💡 Golden Rule: "If you repeatedly need 'the best next item,' think Heap / Priority Queue."
Common Interview Mistakes
Assuming heap[1] is the 2nd smallest element. A heap is NOT globally sorted — only parent vs child order is guaranteed!
Using Max Heap requires storing all N elements (O(N log N)). Use a Min Heap of size K (O(N log K)) instead!
Pushing into the heap without calling heap.Pop() when len > K allows the heap size to grow to N.
Accidentally writing h[i] > h[j] when you intended a Min Heap makes it a Max Heap instead. Double-check comparator direction!
Interview Rules
- 1. Repeated minimum? → Min Heap (
Peek O(1), Pop O(log N)) - 2. Repeated maximum? → Max Heap
- 3. Top K largest? → Min Heap of size K (
O(N log K)time) - 4. Top K smallest? → Max Heap of size K
- 5. Kth largest? → Min Heap top element
- 6. Merge K sorted lists? → Min Heap candidate from each list (
O(N log K)) - 7. Median stream? → Two Heaps: Max Heap (lower half) + Min Heap (upper half)
- 8. Priority scheduling? → Priority Queue storing tuples
(priority, task)
Small Rules
- Rule 1: Heap is NOT fully sorted — only the root is guaranteed minimum or maximum.
- Rule 2: For Top K problems, bound heap size to K to save memory and reduce time to O(N log K).
- Rule 3: Priority Queue items are tuples: (priority_value, payload).
- Rule 4: In algorithms like Dijkstra, handle stale entries by checking visited states upon popping.
- Rule 5: Build Heap (heapify) on an existing array takes O(N) linear time.
Production Thinking
Job Scheduling → Process Critical/High/Normal priority worker queues using Priority Queue
Server Load Balancing → Min Heap (current_load, server_id) to pick least busy server in O(1)
Delayed Tasks & Timers → Min Heap by scheduled execution time (scheduled_timestamp, task)
Streaming Top Products Analytics → Min Heap size 100 for top product sales across continuous multi-terabyte stream
Remember This
Need smallest repeatedly → Min Heap
Need largest repeatedly → Max Heap
Top K largest → Min Heap size K
Top K smallest → Max Heap size K
Kth largest → Min Heap top
Merge K sorted → Min Heap
Median stream → Max Heap + Min Heap
Insert → Bubble Up
Remove top → Bubble Down💡 Golden Rule: "If you repeatedly need 'the best next item,' think Heap / Priority Queue."