SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
  • Inverted Index
  • Trie (Prefix Tree)
  • LRU Cache Design
  • Heap and Priority Queue
  • Bitmaps and Roaring Bitmaps
  • Ring Buffer
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Advanced Data Topics/Data Structures for Scale

Heap and Priority Queue

Always get the biggest (or smallest) item fast. Used for schedulers, top-K and merging sorted streams.

โฑ 12 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A priority queue hands you the most important item first: the smallest, the largest, the earliest deadline. A heap is the structure that makes it fast. You can add an item and remove the top one in O(log n), and look at the top in O(1).

  • Heap rule: every parent is smaller than its children (min-heap) or bigger (max-heap). Siblings are not ordered.
  • Stored in a plain array: parent of i is (i โˆ’ 1) / 2, children are 2i + 1 and 2i + 2. No pointers.
  • Used for: schedulers, timers, delayed jobs, top-K, merging sorted streams and shortest-path search.

02Concept: What is it?

A normal queue gives you the oldest item first. A priority queue gives you the item with the best priority first, whatever order they arrived in. You could keep a sorted list, but then every insert costs O(n). You could scan for the best each time, but then every removal costs O(n). A heap makes both cheap, by keeping the data only partly sorted.

A binary heap is a complete binary tree: every level is full except maybe the last, which fills from the left. Because of that, it fits neatly into an array. The top of the heap is always at index 0, so peek is instant.

The same min-heap, as a tree and as an array
๐ŸŒณTree5 on top, then 20 and 10, then 30, 25
โ†”same data
๐Ÿ“ฆArray [5, 20, 10, 30, 25]index 0 is the smallest
Each parent is smaller than its children. Siblings (20 and 10 under 5) have no order between them.

Push: put the new item at the end of the array (the next free spot in the tree), then sift up: while it beats its parent, swap them. Pop: take the root, move the last item into the root, then sift down: while it loses to a child, swap it with the better child. Each moves along one path, and a tree of n items is only about logโ‚‚(n) levels tall.

๐Ÿง Partly sorted on purpose
A heap is not a sorted list. It only knows the top. That small promise is exactly why it is cheaper than sorting, and why it is the right tool when you only ever need "the next best one".

03Real-Life Example

๐ŸตThe Hospital Waiting Room
Patients do not see the doctor in the order they arrived. The sickest goes first. When a new patient comes in, the nurse does not re-sort the whole room. She just works out where this patient stands against a few others. When the doctor is free, the most urgent patient is already at the front. That is a priority queue: cheap to add, cheap to take the most urgent.
Waiting room
Heap
The most urgent patient
The root (top of the heap)
A new patient joins
Push: add at the end, sift up
The doctor takes the next patient
Pop: remove the root, sift down
Urgency score
Priority or key
Nobody sorts the whole room
Only a path is fixed, O(log n)
Patients with equal urgency
Ties, no promised order
Push 3 into a min-heap
โž•Add at the end[5, 20, 10, 30, 25, 3]
โ†’โ†“3 < parent 10, swap
โฌ†๏ธSift up[5, 20, 3, 30, 25, 10]
โ†’โ†“3 < parent 5, swap
โœ…3 is the top[3, 20, 5, 30, 25, 10]
3 starts at the end (index 5). It beats its parent 10, then its new parent 5, so it ends on top.

04Why Do We Need It?

โšกFast top
Peek is O(1). Push and pop are O(log n).
๐ŸชถTiny memory
Just an array, with no pointers between items.
๐ŸงฎTop-K without sorting
Keep a heap of size K, and handle a stream of any length in O(n log K).
๐Ÿ”€Merging many sources
A heap of the next item from each sorted list merges K lists in O(n log K).
โฑ๏ธAlways the next event
Timers and delayed jobs only need the earliest, which is the top.
๐ŸงญGreedy algorithms
Dijkstra and similar algorithms repeatedly need the best candidate.
When you repeatedly need "the best item right now" while new items keep arriving, a heap is the cheapest answer.

05Where Do We Use It?

๐Ÿ—“๏ธJob and task schedulers
Run the highest-priority job, or the one due soonest, next.
โฐTimers and delayed queues
Keep the next expiry on top. Sleep until then. Used for TTLs, retries and timeouts.
๐Ÿ†Top-K and leaderboards
Trending items, largest files, slowest queries.
๐Ÿ”€K-way merges
Merging sorted log files or sorted shards, and external sorting.
๐Ÿ—บ๏ธShortest paths
Dijkstra and A* pick the closest unvisited node using a heap.
๐Ÿ“ถNetwork and OS scheduling
Packet priority, CPU scheduling and rate shaping.

06Types / Parts / How It Works

Operations and cost

OperationWhat it doesCost
peekRead index 0O(1)
pushAdd at the end, sift upO(log n)
popRemove the root, move the last to the root, sift downO(log n)
heapify (build from n items)Sift down every parent, from the last one back to the rootO(n)
decrease-key / updateChange a priority, then sift up or down. Needs to know the indexO(log n)
search or delete by valueNo order to use, so scanO(n)

Index maths in the array

RelationFormula (0-based)Example for i = 3
Parent of i(i โˆ’ 1) / 2, rounded down1
Left child of i2i + 17
Right child of i2i + 28
Last parentn / 2 โˆ’ 1, rounded downfor n = 10 it is 4

Tricks with heaps

Top-K and the median
Top K largest
โฌ‡๏ธMin-heap of size Kthe smallest of the K sits on top
A new item bigger than the top replaces it
Running median
โฌ†๏ธMax-heap: lower halftop = biggest of the small ones
โฌ‡๏ธMin-heap: upper halftop = smallest of the big ones
Merge K sorted lists
๐Ÿ”€Min-heap of K headspop the smallest, push the next from that list
Which kind of heap to use depends on what you want to keep.
Top-K: O(n log K) Median: O(log n) per number Merge: O(n log K)

Other kinds of heap

KindIdeaWhen it matters
Binary heapTwo children per nodeThe default. Simple and fast in practice
d-ary heap (for example 4-ary)More children, so a shorter treeMany decrease-key calls, better cache use
Binomial / Fibonacci heapCheaper decrease-key in theoryBig graph algorithms. Rarely worth the complexity
Timing wheelBuckets by time slot, not a heapMillions of timers with O(1) insert
VisualizerPush and pop on a heapPress Push a few times and watch each new number sift up. Then press Pop and watch the last item move to the root and sift down. Switch between min-heap and max-heap.
Kind of heap

Numbers to push, in order: 50, 30, 70, 20, 40, 10, 60, 5, 45, 35

As a tree (what you picture)
(empty heap)
As an array (what is really stored). Parent of i is (i โˆ’ 1) / 2. Children of i are 2i + 1 and 2i + 2.
[ ]
โ— the top (root)โ— path the value sifted along
Size
0
height 0
Top of heap
none
peek is O(1)
Last popped
none
Swaps (last op)
0
at most the height
Swaps (total)
0
The heap is empty. Press โ€œPush nextโ€ to add the next number from a fixed list.

The array is not sorted. A heap only promises that every parent is smaller than its children, which is why push and pop move a value along one path only, at most logโ‚‚(n) steps. Keep popping to get the numbers in order.

07How to Use It / Steps / Implementation

Using a priority queue in a design

  1. 1
    Decide what โ€œbestโ€ means
    Smallest deadline, highest priority, lowest cost? That is your key.
  2. 2
    Pick min or max
    Most libraries give a min-heap. For a max-heap, negate the key or flip the comparison.
  3. 3
    Choose the item shape
    Store (key, payload). Compare by key. Add a counter as a tie-break if order among equals matters.
  4. 4
    For top-K, keep a heap of size K
    For the K largest, use a min-heap. Push each item, and pop when the size passes K.
  5. 5
    For timers, peek then sleep
    Look at the top. If it is due, pop and run it. Otherwise sleep until its time.
  6. 6
    Plan for changing priorities
    Either support decrease-key with an index map, or push a new entry and ignore the stale one when it surfaces (lazy deletion).
  7. 7
    At scale, shard it
    One heap on one machine is fine for millions of items. For more, partition by key or time, and keep a heap per partition.
Min-heap push and pop (TypeScript)
class MinHeap {
  a: number[] = [];
  push(v: number) {
    const a = this.a; a.push(v);
    let i = a.length - 1;
    while (i > 0) {
      const p = (i - 1) >> 1;
      if (a[p] <= a[i]) break;
      [a[p], a[i]] = [a[i], a[p]]; i = p;
    }
  }
  pop(): number | undefined {
    const a = this.a; if (!a.length) return undefined;
    const top = a[0], last = a.pop()!;
    if (a.length) {
      a[0] = last; let i = 0;
      for (;;) {
        const l = 2 * i + 1, r = l + 1; let m = i;
        if (l < a.length && a[l] < a[m]) m = l;
        if (r < a.length && a[r] < a[m]) m = r;
        if (m === i) break;
        [a[i], a[m]] = [a[m], a[i]]; i = m;
      }
    }
    return top;
  }
}
๐Ÿ’กDelayed jobs
A delayed queue is a min-heap on "run at" time. The worker peeks the top, sleeps until it is due, then pops and runs it. Redis does the same with a sorted set scored by time.

08Key Terms to Know

TermMeaning in easy words
Priority queueAn abstract queue that returns the best item first
HeapA tree where every parent is ordered against its children
Min-heap / max-heapSmallest / largest item on top
Complete binary treeAll levels full except the last, which fills from the left
RootThe top node, at index 0 of the array
Sift up (bubble up)Swap a new item upward while it beats its parent
Sift down (bubble down)Swap an item downward with its better child until it fits
HeapifyTurn an unsorted array into a heap in O(n)
Decrease-keyImprove the priority of an item already in the heap
Lazy deletionLeave stale entries in the heap and skip them when they reach the top
Top-KThe K best items out of a large set or stream
Tie-breakA second field (such as a counter) to order equal priorities

09Pros, Cons and Trade-offs

โœ… Pros
  • O(1) peek, O(log n) push and pop
  • Stored in a plain array, no pointers
  • Building from n items takes only O(n)
  • Great for top-K and merging streams
  • Simple to write and well supported
โš ๏ธ Cons
  • Not sorted: cannot list items in order without popping all
  • Searching or deleting by value is O(n)
  • No order among equal priorities (not stable)
  • Updating a priority needs an index map
  • Poor fit for a distributed system without partitioning

Trade-offs

ChoiceWe gainWe lose
Heap vs sorted listFast insertsNo full order
Heap vs balanced treeSimpler, lower constant costNo range queries or ordered scan
Heap vs timing wheelExact order of timersO(log n) instead of O(1) for huge timer counts
Lazy deletionNo index map neededHeap holds stale items for a while
d-ary heapFewer levels, better cache useMore comparisons per level
One heap vs partitioned heapsSimplicityScale (but global order is lost across partitions)

10Common Problems and Mistakes

Common mistakes

  1. Using a max-heap for top-K largest. You want a min-heap of size K, so you can see the weakest of the K and throw it out cheaply.
  2. Assuming the array is sorted. Only index 0 is guaranteed. Iterating the array does not give sorted order.
  3. Searching a heap for a value. That is O(n). Keep a map from item to index if you need updates.
  4. Expecting FIFO among ties. Equal priorities may come out in any order. Add a sequence number.
  5. Off-by-one index maths. Be careful whether your array starts at 0 or 1.
  6. Mutating an item's priority in place. The heap does not know. Re-sift it or push a new entry.
  7. One heap under many threads. Needs a lock. A hot lock on a scheduler becomes the bottleneck.

Things to watch

๐Ÿ“ˆGrowing size
A heap that only gets pushes can grow without bound. Cap it, or expire items.
๐Ÿ•ฐ๏ธClock changes
A heap of wall-clock times is thrown off when the clock jumps. Use a monotonic clock.
๐ŸชฆStale entries
With lazy deletion, count stale entries and rebuild when they dominate.
๐Ÿ”’Contention
A global heap can serialise all workers. Partition it.

11Real-World Examples

๐ŸPython heapq / Java PriorityQueue
Standard library binary heaps, used everywhere from schedulers to Dijkstra.
๐ŸงLinux timers and schedulers
Use trees and timer wheels, which solve the same โ€œnext dueโ€ problem.
๐ŸงฐRedis sorted sets
Often used as a delayed queue by scoring jobs with their run time.
๐Ÿ“จKafka and message brokers
Delay and retry features rely on time-ordered structures like heaps or timing wheels.
๐Ÿ”Search engines
Keep a heap of the best K hits per shard, then merge the shard results.
๐Ÿ—บ๏ธRouting and maps
Dijkstra and A* are the heart of route planning and use a priority queue.
Mini case: top 3 slowest requests in a stream
๐ŸŒŠStream of latencies120, 80, 300, 45, 210 ...
โ†’โ†“push, pop if size > 3
๐Ÿ”ปMin-heap, size 3holds 120, 300, 210
โ†’โ†“at the end
๐Ÿ†The 3 slowest
A min-heap of size 3 holds the three slowest so far. The top is the least slow of them.

12Related Topics to Read Next

LRU Cache Designโ†’

Another structure that answers โ€œwhich one goes nextโ€ in constant time.

Task Queues, Workers and Scheduled Jobsโ†’

Delayed and priority jobs use this structure.

Message Queuesโ†’

Priority and delay queues.

Skip Listsโ†’

An ordered alternative that supports range scans.

Trie (Prefix Tree)โ†’

Top-K suggestions can be merged with a heap.

Rate Limitingโ†’

Timers and expiry often use a heap or timing wheel.

MapReduceโ†’

K-way merges of sorted data in the shuffle step.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”Heap: complete binary tree in an array, parent beats children.
  • โœ”Index: parent (i โˆ’ 1) / 2, children 2i + 1 and 2i + 2.
  • โœ”Cost: peek O(1), push and pop O(log n), heapify O(n).
  • โœ”Push: add at the end, sift up. Pop: root out, last to root, sift down.
  • โœ”Top-K largest: min-heap of size K. Median: two heaps.
  • โœ”Merge K lists: heap of the next item from each, O(n log K).
  • โœ”Not good at: searching, sorted listing, stable ties.
  • โœ”One line: โ€œOnly the top is promised, and that is all a scheduler ever needs.โ€
โ† Previous
LRU Cache Design
Next โ†’
Bitmaps and Roaring Bitmaps