Skip to main content

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.

1[0]3[1]2[2]7[3]4[4]5[5]8[6]0123456heap1327458children of i: 2i + 1, 2i + 2 Β· parent of i: (i βˆ’ 1) // 2

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​

OperationBig-OPython heapq
Peek minO(1)heap[0]
PushO(log(n))heappush
Pop minO(log(n))heappop
Push then popO(log(n))heappushpop
Build from listO(n)heapify, not n pushes
Search / remove arbitraryO(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​

PatternUse whenCostExample
Top-k with a size-k heapk largest/closest from n items, or a streamO(n log k)K Closest Points, Kth Largest
Two heapsRunning median, or balancing two halvesO(log n) per addFind Median from Data Stream
K-way mergeMerge k sorted lists/arrays; kth smallest in a sorted matrixO(N log k)Merge k Sorted Lists
Greedy schedulingAlways run the most urgent or most frequent nextO(n log n)Task Scheduler, Meeting Rooms II
Shortest pathDijkstra: pop the closest unsettled nodeO(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​

Source

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​

Source

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.