Heaps & Priority Queues 101
Intermediate · 4 chapters · 7 min read · Keep the best k items at hand and always process the most urgent one next.
Practise this in the app All guides
What a heap is and when to use one
Always know the smallest
A heap is a binary tree stored in an array where every parent is no larger than its children (a min-heap). That single rule means the smallest element is always at index 0. Pushing a new element or popping the smallest takes O(log n), and peeking at the smallest is O(1). A priority queue is the abstract idea ("give me the most important item next"); a heap is how it is almost always implemented.
Python's heapq module works on a plain list and gives a min-heap only. For a max-heap, push negated values (-x) or tuples with a negated key.
Signals in a problem statement
- "k-th largest / k-th smallest", "top k frequent", "k closest points".
- "Repeatedly take the two largest (or smallest) and combine them" — a simulation that always needs the current extreme.
- "Merge k sorted lists or arrays".
- "Median of a stream" — two heaps.
- "Schedule tasks", "choose projects with limited capital", "meeting rooms needed" — greedy choices that always pick the best currently available option.
- Shortest paths with weights (Dijkstra), covered in the Graphs card.
Heap or sort?
If you need everything in order once, sorting is simpler. A heap wins when items arrive over time, when you only need the top k of a large n (O(n log k) instead of O(n log n)), or when the set changes between choices. Saying this trade-off out loud is a mark of maturity.
Mental model
Think of a hospital emergency ward: patients arrive in any order, but the doctor always sees the most urgent one next. The heap is the triage desk.
Core patterns with templates
1. Basic operations
import heapq
h = []
heapq.heappush(h, 5)
heapq.heappush(h, 2)
smallest = heapq.heappop(h) # 2
heapq.heapify(h) # O(n) for an existing list
top = h[0] if h else None # peek
2. Size-k heap for the k-th largest
Keep a min-heap of the k largest values seen; its top is the answer.
def kth_largest(nums, k):
h = []
for x in nums:
heapq.heappush(h, x)
if len(h) > k:
heapq.heappop(h)
return h[0]
Example: [3, 2, 1, 5, 6, 4], k = 2 keeps [5, 6], answer 5.
3. Max-heap by negation (simulation)
def last_stone_weight(stones):
h = [-s for s in stones]
heapq.heapify(h)
while len(h) > 1:
a, b = -heapq.heappop(h), -heapq.heappop(h)
if a != b:
heapq.heappush(h, -(a - b))
return -h[0] if h else 0
4. Tuples as keys
def k_closest(points, k):
return heapq.nsmallest(k, points, key=lambda p: p[0] * p[0] + p[1] * p[1])
When pushing tuples yourself, add a tie-breaker (such as an index) before any object that cannot be compared: (dist, i, point).
5. Two-phase greedy: unlock, then pick the best
Sort options by their requirement; as your resources grow, push every newly affordable option into a max-heap, then take the best one.
def max_capital(k, w, profits, capital):
projects = sorted(zip(capital, profits))
h, i = [], 0
for _ in range(k):
while i < len(projects) and projects[i][0] <= w:
heapq.heappush(h, -projects[i][1])
i += 1
if not h:
break
w -= heapq.heappop(h)
return wComplexity, mistakes and edge cases
Complexity
| Operation | Time |
|---|---|
heappush, heappop | O(log n) |
peek h[0] | O(1) |
heapify | O(n) |
| top k of n with a size-k heap | O(n log k) |
nsmallest(k, ...) / nlargest | O(n log k) |
Space is O(k) for a bounded heap, O(n) otherwise.
Common mistakes
- Forgetting Python only has a min-heap. For the largest values, negate on push and on pop.
- Using a max-heap of size n for the k-th largest when a min-heap of size k is cheaper and is what the interviewer is fishing for.
- Comparing uncomparable objects. Tuples with equal first elements compare the second element; if that is a
ListNodeor dict, Python raisesTypeError. Insert a counter as a tie-breaker. - Modifying a heap list directly (for example
h[3] = 7) without restoring the heap property. - Popping from an empty heap. Check
if hfirst, especially in simulations. - Taking square roots for distance comparisons. Squared distances order the same way and avoid floating point.
Edge cases
k equal to n, k = 1, duplicate values, negative numbers, an empty heap at the end of a simulation, and projects that can never be afforded.
Quickselect as an alternative
For a one-off k-th largest on an array, quickselect partitions around a random pivot and recurses into one side only, averaging O(n) time. It is worth mentioning as a follow-up, but the heap solution is safer to code under pressure and is perfectly acceptable for most interviews.
Variations and practise
How interviewers twist it
- Top k frequent elements. Count with a
Counter, then keep a size-k heap of(count, value). A bucket sort by frequency gives O(n) as a follow-up. - Merge k sorted lists. Push the head of each list as
(value, list_index, node); pop the smallest, push its successor. O(N log k). - Median of a data stream. A max-heap for the lower half and a min-heap for the upper half, kept within one element of each other in size. The median is the top of one heap or the average of both tops.
- Task scheduling with cooldown. A max-heap of remaining counts plus a queue of tasks waiting out their cooldown.
- Meeting rooms. Sort by start time and keep a min-heap of end times; the heap size is the number of rooms in use.
- Lazy deletion. When items must be removed from the middle, mark them as deleted and discard them when they reach the top.
How to explain it
Say what the heap holds and what its top means: "a min-heap of the k largest values so far; its top is the k-th largest". That phrasing also makes the O(n log k) cost obvious.
Practise
The problems below cover a size-k heap, a max-heap simulation, closest points with a distance key, and a two-phase greedy that unlocks options as capital grows. For each one, decide first whether you need a min-heap or a max-heap, and what the tie-breaker is.
Practise
Easy
- 2080. Last Stone Weight
- 2081. Take Gifts From the Richest Pile
- 2086. Does This Array Form a Min-Heap
- 2091. Array After Inserting Into a Min-Heap
- 2092. Swaps Needed to Heapify
- 2093. Level Totals of a Heap Array
- 2094. Flip a Min-Heap Into a Max-Heap
- 2095. Remove an Arbitrary Slot From a Min-Heap
- 2096. Lower a Priority Inside a Min-Heap
- 2097. Heapsort Midway Snapshot
- 2098. Kth Smallest Without Emptying the Heap
- 2099. The K Lowest Exam Scores
- 2100. Kth Highest Distinct Sensor Reading
- 2101. Podium Total After Each Race
- 2102. Kth Place on a Growing Leaderboard
- 2103. Finishing Positions From Scores
- 2104. Strongest K Readings Kept in Original Order
- 2105. The K Longest Words
- 2106. Students With the Lowest Averages
- 2107. Most Items Within a Budget
- 2108. Bargain Hunter's Daily Purchase
- 2109. Fewest Coins to Reach a Target
- 2110. Sign Flip Budget
- 2111. Raise the Floor
- 2112. Cheapest Way to Splice Cables
- 2114. Alternating Biggest-Smallest Draw
- 2115. Sum Between Two Ranks
- 2116. Average After Discarding the Extremes
- 2117. Sort a Nearly-Sorted Sequence
- 2118. Merge Sorted Shelves
- 2119. Merge Three Sorted Chains
- 2120. Service Desk Call Order
- 2122. When Is the Laundry Done
- 2123. Reassembling Out-of-Order Packets
Medium
- 2082. Kth Largest Element in an Array
- 2083. K Closest Points to Origin
- 2087. Is This Tree a Max-Heap
- 2088. Count Max-Heap Arrangements
- 2089. Fewest Studios for All Recordings
- 2113. Pair-Up Training Sessions
- 2121. When Does My Print Job Finish
- 2124. Shuttle Capacity Check
- 2125. Most Festival Days Attended
- 2126. Common Idle Slots
- 2127. Next Booking After Each Slot
- 2128. Chair for the Guest of Honour
- 2129. Library Seat Spreading
- 2130. Assigning Jobs to Render Rigs
- 2131. Restaurant Table Seating
- 2132. Shortest Job First Waiting Time
- 2133. Preemptive Priority Scheduler
- 2134. Letters Without Equal Neighbours
- 2135. Spelling Without Triples
- 2136. Largest String With a Repeat Cap
- 2137. Fewest Deletions for Unique Letter Counts
- 2138. Erase the Smallest Before Each Star
- 2139. Top Students by Feedback Score
- 2140. Fewest Labels Left After K Removals
- 2141. Kth Biggest Among Huge Numbers
- 2142. Kth Smallest in a Sorted Grid
- 2143. K Pairs With the Smallest Sums
- 2144. Kth Smallest Ratio From a Sorted List
- 2145. Nth Number Built From Given Primes
- 2146. Bell Towers Ringing Schedule
- 2147. Sort a Chain of Ascending Runs
- 2148. Prune the K Heaviest Links
- 2149. Kth Heaviest Tree Level
- 2150. K Largest Root-to-Leaf Totals
- 2151. Median After Each Reading
- 2152. Level the Towers
- 2153. Best Use of Extra Tutors
- 2154. Placing Extra Lampposts
- 2155. Worst-Fit Truck Loading
- 2156. Merging Files K at a Time
- 2157. Crew Leveling the Hill
- 2158. Recruiting From Both Ends of the Line
- 2159. Regional Qualifiers Then Finals
- 2160. Best K Rewards From Weaker Rivals
- 2161. Capped Picks From Each Shelf
- 2162. Keep the Balance Afloat
- 2163. How Far Can the Hiker Climb
- 2164. Unit Jobs With Deadlines and Profits
- 2165. Split Cards Into Consecutive Runs
- 2166. Chains of Length Three or More
- 2167. Mark-and-Collect Score
- 2168. Lake Drying Schedule
- 2169. Peak Reading in Each Window
- 2170. Longest Steady Stretch
- 2171. Most Common Item in Each Window
- 2172. Stepping Stones Max Score
- 2173. Kth Largest Corner XOR
- 2174. Slice of Sorted Subarray Totals
- 2175. Corrected Price Feed
- 2176. Matching Buy and Sell Orders
- 2177. Menu Ratings Board
- 2178. Newest Posts Feed
- 2179. Most-Repeated Pop Stack
- 2180. Smallest Valid Build Order
- 2181. Cheapest Walk Across a Toll Grid
- 2182. Fewest Walls to Break
- 2183. Most Reliable Relay Route
- 2184. Wire All the Kiosks
- 2185. Count the Fastest Routes
- 2186. Fastest Route With Fewest Hops
- 2187. Cheapest Route Within K Transfers
- 2188. One Free Ride
- 2189. Transit With Platform Waits
- 2190. Town With the Fewest Neighbours in Range
- 2191. Distance to the Nearest Hospital
- 2192. Roads on Some Fastest Route
- 2193. Best Shelves Near the Entrance
Hard
- 2084. IPO
- 2085. Trapping Rain Water II
- 2090. Median of Every Window
- 2194. Top-K Total Under Updates
- 2195. Letters Spaced At Least K Apart
- 2196. Smallest Range Touching Every List
- 2197. Kth Smallest Sum Picking One per Row
- 2198. Kth Largest Subsequence Sum
- 2199. Sum of the K Best Stretches
- 2200. Room Usage Champion
- 2201. Fewest Charging Stops for an EV
- 2202. Workshop Marathon
- 2203. Strongest Squad
- 2204. Cheapest Crew Paid by Quality
- 2205. Balance After Discarding a Third
- 2206. Curated Exhibit Score
- 2207. Rewind the Sum Machine
- 2208. Narrowest Spread With Doubling and Halving
- 2209. Splitting Workers to Build Blocks
- 2210. Smoothest Staircase Cost
- 2211. Trading One Unit a Day
- 2212. Non-Adjacent Booth Picks
- 2213. Best Pair of Signal Posts
- 2214. Plate Racks
- 2215. Shortest Covering Window per Query
- 2216. City Outline Keypoints
- 2217. Rendezvous Tower
- 2218. Threshold Grid Exploration
- 2219. Gate Timers Grid
- 2220. Waypoints Reached Within a Step Budget
- 2221. Two Shipments, One Destination
- 2222. Second-Fastest Arrival With Traffic Lights
- 2223. Kth Shortest Walk
- 2224. Cheapest Toll Route Before the Deadline
- 2225. Project Finish With Limited Workers
- 2226. Earliest Slot for Task Zero First
- 2227. Heaviest Tree After Degree Trimming