Heaps and priority queues interview questions
Min-heaps by hand and with heapq: the k largest, merging sorted feeds, running medians and greedy choices that always take the smallest or biggest next.
– interview-ready · 10 questions in this topic
– of 10 tried
Saved on this device. Interview-ready means you got it right on two different days. Guesses and hints count for less.
Questions
- Push values into a min-heap by handPredict
- The k-th biggest readingFill the blank
- Merge many sorted feeds into onePredict
- The k depots nearest the warehousePredict
- Fewest time slots when each job type needs a cooldownPredict
- Median after each new readingPredict
- Smash the two heaviest rocks until one is leftPredict
- Cheapest way to join ropes into onePredict
- How a binary heap worksPredict
- Heap, sort or quickselect?Pick the fix
Practise this topic
Flashcards · 20
Flip, then say if you knew it. Needs JavaScript; every answer is also on its question page.
Quick quiz · 10 questions
One exercise per question, checked as you go. Needs JavaScript.
Mock interview · 2 sets
Timed, out loud, then tick what you covered. Needs JavaScript.
Quick facts
Recall the answer first, then tap Show to check.
heapqis a min-heapheapqkeeps the smallest item at index 0 of a plain list;heappushandheappopare O(log n).heapq.heapifyheapify(xs)rearranges a list into a heap in place in O(n), faster than n separate pushes.heapq.nlargestandnsmallestnlargest(k, xs)uses a size-k heap, O(n log k); for k close to n,sortedis faster.Kotlin
PriorityQueuejava.util.PriorityQueueis a min-heap by default; passcompareByDescendingorreverseOrder()for a max-heap.Tuples as heap keys
heapq compares whole tuples, so
(priority, counter, item)breaks ties by the counter and never compares the items.
Printable cheat sheet · Review your weak spots in this topic
Share your progress
Sources: Topic outline informed by the Tech Interview Handbook by Yangshun Tay and the NeetCode 150 pattern grouping by neetcode-gh, both MIT licensed. Every problem, solution and explanation is written by Best Latest Apps. Credits and license