Heaps
Use a heap when you repeatedly need the smallest (or largest) item of a collection that keeps changing. Sorting once is cheaper if the collection doesn't change.
Figure HEAP-1: A min-heap is a complete binary tree stored as an array. Every parent is β€ its children; siblings are in no order. Amber is index 1 and its children, found by arithmetic rather than pointers.
Time Complexityβ
| Operation | Big-O | Python heapq |
|---|---|---|
| Peek min | O(1) | heap[0] |
| Push | O(log(n)) | heappush |
| Pop min | O(log(n)) | heappop |
| Push then pop | O(log(n)) | heappushpop |
| Build from list | O(n) | heapify, not n pushes |
| Search / remove arbitrary | O(n) | Use lazy deletion instead |
heapq is a min-heap only. For a max-heap, push -x. For objects, push tuples (priority, tiebreak, item): without the tiebreak, equal priorities make Python compare the items and raise.
Common Approaches to Heap Questionsβ
| Pattern | Use when | Cost | Example |
|---|---|---|---|
| Top-k with a size-k heap | k largest/closest from n items, or a stream | O(n log k) | K Closest Points, Kth Largest |
| Two heaps | Running median, or balancing two halves | O(log n) per add | Find Median from Data Stream |
| K-way merge | Merge k sorted lists/arrays; kth smallest in a sorted matrix | O(N log k) | Merge k Sorted Lists |
| Greedy scheduling | Always run the most urgent or most frequent next | O(n log n) | Task Scheduler, Meeting Rooms II |
| Shortest path | Dijkstra: pop the closest unsettled node | O(E log V) | Graphs β Dijkstra |
Top-k: keep the opposite heapβ
For the k largest, keep a min-heap of size k: its root is the smallest of the winners, so it's the one to evict.
import heapq
def kthLargest(nums, k):
heap = []
for n in nums:
heapq.heappush(heap, n)
if len(heap) > k:
heapq.heappop(heap) # drop the smallest; the k largest remain
return heap[0]
heapq.nlargest(k, nums) does the same in one line.
Two heaps: running medianβ
A max-heap holds the lower half, a min-heap the upper half. Keep their sizes within one, and the median is at the roots.
import heapq
class MedianFinder:
def __init__(self):
self.lo, self.hi = [], [] # lo: max-heap via negation, hi: min-heap
def addNum(self, num):
heapq.heappush(self.lo, -num)
heapq.heappush(self.hi, -heapq.heappop(self.lo)) # largest of lo moves up
if len(self.hi) > len(self.lo):
heapq.heappush(self.lo, -heapq.heappop(self.hi)) # rebalance
def findMedian(self):
if len(self.lo) > len(self.hi):
return -self.lo[0]
return (-self.lo[0] + self.hi[0]) / 2
Example Solutionsβ
Task Schedulerβ
Explanation on LeetCode discussions.
Solution 1: Math Approachβ
- Case 1: No idle gaps required - answer is length of tasks
- Case 2: Idle gaps required - (maxFreq - 1) * (n + 1) + nMax
- (maxFreq - 1) - maximum occurences of character with maximum occurences except last occurence
- (n + 1) - number of elements in each repeated interval
A _ _ - nMax - number of characters in last occurence
def leastInterval(self, tasks, n):
store = {}
for i in tasks:
store = 1 + store.get(i, 0) # default 0 if not found
lst = sorted(store.values(), reverse=True)
maxFreq = lst[0]
nMax = lst.count(maxFreq)
caseTwo = (maxFreq - 1) * (n + 1) + nMax
return max(len(tasks), caseTwo)
Time Complexity: O(n) for counting tasks.
Space Complexity: O(1) for fixed dictionary size of 26 characters.
Solution 2: Heap and Queueβ
Explanation by NeetCode.
def leastInterval(self, tasks, n):
count = Counter(tasks)
maxHeap = [-cnt for cnt in count.values()]
heapq.heapify(maxHeap)
time = 0
q = deque() # pairs of [-cnt, idleTime]
while maxHeap or q:
time += 1
if maxHeap:
cnt = 1 + heapq.heappop(maxHeap)
if cnt: # Count not zero: add back to queue with new idleTime
q.append([cnt, time + n])
if q and q[0][1] == time:
heapq.heappush(maxHeap, q.popleft()[0])
return time
Time Complexity: O(n + m) where n is len(tasks) and m is length of idle interval.
Space Complexity: O(1) for fixed dictionary size of 26 characters.