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.
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.
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).
| Operation | In a heap |
|---|---|
| Get the top-priority item | Instant - it's always at the top |
| Remove the top item | Fast - re-organise in O(log n) |
| Add an item | Fast - slot it in, O(log n) |
| Keep everything fully sorted | NOT 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.
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.
Related lessons
Visiting Every Node: Traversals
Once you have a tree, you often need to visit every node โ but in what order? The four traโฆ
Trees, Heaps & TriesTries: The Autocomplete Structure
How does a search box suggest completions the instant you type? Often, a trie โ a tree thaโฆ
Data Structures & AlgorithmsStacks, Queues & Beyond
Some structures aren't about storage but about *order of access* โ stacks (last-in-first-oโฆ