๐ŸŒฒ
๐ŸŒฒ Trees, Heaps & Tries ยท DS-201 ยท Session 4 of 6

Heaps & Priority Queues

A heap is the structure that always hands you the most important item next โ€” instantly. It powers task schedulers, 'top N' problems, and famous algorithms, and it's cleverly simple inside.

โฑ 9 min read๐Ÿ“… Updated 2026-08-09๐Ÿ“Š Tables, charts & examples

Imagine a queue where instead of first-in-first-out, you always take the most important item next - a hospital treating the most urgent patient, a scheduler running the highest-priority task. That's a priority queue, and the structure that makes it fast is a heap. A heap always gives you the top-priority item instantly, and stays organised as items come and go. It's cleverly simple inside, and it powers a surprising amount of real software. This session covers heaps.

๐Ÿ“Œ Worked example
The emergency room, not the queue. A hospital doesn't treat patients first-come-first-served - it treats the most urgent first, no matter when they arrived. That's a priority queue, and a heap is how you build it efficiently: each new patient is slotted in, and the most critical one is always instantly at the top, ready to be seen next. When they're treated and leave, the next-most-critical rises to the top automatically. You never re-sort the whole waiting room; the heap keeps just enough order to always surface the most important case fast. The same structure runs task schedulers, GPS routing (Dijkstra always expands the nearest node next), and 'top 10' feeds - anywhere a program must repeatedly grab the most important item from a changing set. It's the quiet engine of 'what's next?' done by priority instead of arrival.

Always the most important, instantly

A heap keeps its collection so that the highest-priority item is always at the top, ready to grab - without keeping everything fully sorted (which would be more work).

OperationIn a heap
Get the top-priority itemInstant - it's always at the top
Remove the top itemFast - re-organise in O(log n)
Add an itemFast - slot it in, O(log n)
Keep everything fully sortedNOT needed - just the top matters

The key insight is that a heap does <i>less</i> work than fully sorting: it only guarantees the top item is the most important, not that everything is in order. That's exactly what a priority queue needs - you only ever want the next most important item - and doing less means it's fast. The stack's <a href='/stack/larzheap'>larzheap</a> is exactly this: push items, pop the top, peek, with min or max priority.

How a binary heap works

A binary heap is a tree with one rule (every parent is higher-priority than its children), cleverly stored in a plain array.

๐ŸŽฏ
One rule - parent beats children - keeps the top on top with little work. A heap is a binary tree where every node is higher-priority than its children. That single rule means the highest-priority item is always at the root (the top). When you remove the top, you move the last item up and let it 'sink' down past higher-priority children until the rule holds again - just a path down the tree, O(log n). Adding does the reverse: place the item at the bottom and let it 'bubble up'. Cleverly, the tree is stored in a flat array (a node's children are at simple index positions), so there are no pointers - it's just an array with clever index math. Simple rule, clever storage, fast priority access.

The priority engine

  • A priority queue always gives the most important item next - a heap makes it fast.
  • A heap does less than sorting - only the top is guaranteed highest-priority.
  • One rule: every parent beats its children, so the top is always on top.
  • Push/pop are O(log n) (bubble up / sink down); stored cleverly in a flat array - see larzheap.

๐Ÿงฉ Do it with LarzOS

Turn this lesson into action with the exact free tools and AI workflows for the job:

๐ŸŽฏ Key takeaways

  • A priority queue always gives you the most important item next; a heap is the structure that makes it fast.
  • A heap does less work than fully sorting - it only guarantees the top item is highest-priority, which is all you need.
  • A binary heap follows one rule (every parent beats its children), so the top is always at the root.
  • Push and pop are O(log n) (bubble up / sink down), and it's stored cleverly in a flat array - see larzheap.

Frequently asked

Why use a heap instead of just keeping a sorted list and taking the first item?

A sorted list would let you take the highest-priority item instantly (it's at the front), but keeping the list sorted as items are added is slow, and that's exactly the problem a heap solves more efficiently - it's the classic trade-off between doing work up front versus doing just enough. With a sorted list: taking the top item is fast (it's at the front, O(1) to read, though removing from the front of an array shifts everything, and from a sorted structure varies), but inserting a new item in the right position to keep the list sorted is O(n), because you have to find the position and shift elements to make room. So if items are frequently added (which is typical for a priority queue - a scheduler constantly getting new tasks), the sorted-list approach pays O(n) on every insertion, making it slow overall. A heap does better by not keeping everything fully sorted - it only maintains enough structure to guarantee the top item is the highest-priority, which is all a priority queue actually needs. This 'just enough order' means both inserting a new item and removing the top item are O(log n) - fast - because each operation just involves an item bubbling up or sinking down a path of the tree (of height log n), rather than reorganising the whole collection. The insight is that fully sorting is more work than necessary when you only ever want the single most important item at a time: a heap provides fast access to just the top while spending far less effort maintaining order among the rest. So compared to a sorted list, a heap trades the sorted-list's fully-ordered-but-slow-to-maintain property for a partially-ordered-but-fast-to-maintain one, and since a priority queue only needs the top, this is a great trade. The result: with a heap, both adding items and taking the top are O(log n), which is much better than the sorted list's O(n) insertion when items are frequently added. There are cases where a sorted list is fine - if you add all items once and then just repeatedly take the top without adding more, or if the collection is tiny, the simplicity of a sorted list might be acceptable. But for the common priority-queue scenario of a changing collection where you continually add items and take the highest-priority one (schedulers, event simulations, Dijkstra's algorithm, streaming top-N), a heap's fast insertion is decisively better, which is why heaps are the standard implementation of priority queues. The heap's cleverness is precisely doing less than full sorting while still giving instant access to the most important item, and that efficiency on a changing collection is why you use it over a sorted list. It's a beautiful example of a structure designed to be just organised enough for its purpose and no more, which is what makes it fast.

Where are heaps actually used in real software?

Heaps (and the priority queues they implement) show up throughout real software wherever a program needs to repeatedly get the most important or most extreme item from a changing collection - which turns out to be common across many domains. Here are prominent real uses. Task scheduling: operating systems and applications use priority queues to decide what to run next based on priority - a scheduler picks the highest-priority ready task, and heaps make 'get the most urgent task' fast even as tasks are constantly added. Anything with prioritised job processing (print queues with priorities, job systems, background task runners) can use a heap. Graph algorithms: several fundamental and widely-used algorithms rely on priority queues - most famously Dijkstra's shortest-path algorithm (used in GPS navigation, network routing, and mapping to find shortest routes) uses a heap to always expand the nearest unvisited node next, and Prim's minimum-spanning-tree algorithm similarly. These algorithms would be much slower without a heap. Top-N / 'find the largest/smallest K' problems: when you need the top few items from a large or streaming dataset (the 10 highest scores, the nearest neighbours, the most frequent items), heaps efficiently maintain the top-N without sorting everything - very common in data processing, recommendations, and analytics. Event-driven simulation: simulations process events in time order, using a priority queue keyed by event time to always handle the next-soonest event - used in modelling, games, and systems simulation. Merging sorted sequences: heaps efficiently merge many sorted streams (used in external sorting of huge datasets and in databases), by always taking the smallest current element across the streams. Heapsort: heaps give a sorting algorithm (though other sorts are often preferred, heapsort has guaranteed O(n log n) and is used in some contexts). Median maintenance and streaming statistics: clever use of two heaps can track a running median of streaming data. Networking and bandwidth management: prioritising packets or requests. Compression: Huffman coding (used in data compression) builds its tree using a priority queue. Beyond these, any time you catch a program repeatedly needing 'the most/least X from a set that keeps changing', a heap is likely the right tool, and it's often used under the hood in libraries and systems you rely on. So heaps are far from an academic curiosity - they're a workhorse behind schedulers, navigation and routing, top-N and streaming problems, simulations, and important algorithms, quietly making 'get the most important item next' fast in software people use daily. Understanding heaps means you recognise these patterns and can reach for a priority queue when your problem fits - and appreciate what's happening inside the many systems that use them. The stack's larzheap lets you use a priority queue directly for exactly these kinds of 'always get the top item' needs, and understanding it illuminates a structure that's genuinely everywhere in practical computing.

Session 4 of 6 complete

Next up: Tries: The Autocomplete Structure

Continue to Session 5 โ†’

Related lessons

More in this course

Course home → · Browse all courses →