Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Data Structures and Algorithms
  • What a Data Structure Is, and How Memory Works
  • Arrays and Dynamic Arrays: Full? Get a Box Twice the Size
  • Linked Lists: A Chain of Clues, Built in Python
  • Stacks: Last In, First Out, With the Undo Button
  • Queues: First In, First Out, With a Ring of Cells
  • Hash Tables: The Name Tells You Where to Look
  • Binary Search Trees: Smaller Left, Bigger Right, Half Gone at Every Look
  • Tree Traversals: In-Order, Pre-Order and Post-Order as a Tour of the House
  • Heaps and Priority Queues: Most Urgent First, Without Searching the Room
  • Graphs and Breadth-First Search (BFS): Fewest Hops, Level by Level
  • Big-O: Reading Cost From Code, With Handshakes and a Guest Book
  • Recursion: Russian Dolls, the Base Case and the Call Stack
  • Linear vs Binary Search: Page by Page, or Open in the Middle
  • Insertion Sort: Take the Next Card and Slide It Left Until It Fits
  • Merge Sort: Split the Pile, Then Merge Two Sorted Piles
  • Quick Sort: Line Up Around One Friend, Then Repeat on Each Side
  • Depth-First Search (DFS): Go Deep, Back Up, Mark Where You've Been
  • The Two Pointers Technique: Find a Pair in One Pass Instead of Every Pair
  • The Sliding Window Technique: One In, One Out
  • Greedy Algorithms: The Best-Looking Choice, Right Now
  • Dynamic Programming: Work It Out Once, Write It Down, Read It Back
  1. Blog
  2. /
  3. Data Structures and Algorithms
  4. /
  5. Data Structures

Heaps and Priority Queues: Most Urgent First, Without Searching the Room

A hospital waiting room where urgency 1 goes first. King of the hill shows how a min-heap works, a row of seats shows how it lives in an array, then add climbs up, poll sinks down, and Python's heapq does it for you.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Data Structures

What you will learn

  • Explain a min-heap with the king-of-the-hill game
  • Store a heap in a plain array using the parent and child seat rules
  • Walk add (sift up) and poll (sift down) step by step
  • Use Python's heapq and state the cost of each heap operation

Before you start

  • Binary Search Trees
  • Arrays and Dynamic Arrays

A hospital waiting room. Four patients arrive in this order: Emma, Jack, Tom and Kate. Each gets an urgency number, and urgency 1 is the most urgent. So Kate goes first, even though she came in last.

The plain way: each time the doctor is free, check every patient and find the smallest number. With four patients that's four checks. With a thousand people waiting, it's a thousand checks every single time. We want the most urgent patient on top, ready, every time. That's what a heap gives you.

King of the hill

Here's a playground game. On this hill, the smallest number wins, and every kid beats the two kids below them. So 2 is the king, at the top.

  • A new kid, 1, joins at the bottom. 1 beats 5, so they swap. 1 beats 2, so they swap again. 1 is the new king.
  • Now the king leaves. The last kid, 5, jumps to the top, then swaps with the smaller of the two below, which is 2. So 2 is king again.

Each kid only moves along one path, top to bottom, so it's just a few swaps even on a huge hill. A hill where every kid beats the two below is called a heap, and the king, the most urgent, is always on top. A priority queue is the job (serve the most urgent next); a heap is the usual way to do it.

A hill in a row of seats

A computer keeps the hill in a plain row of seats, numbered from 0, level by level from the top.

A heap drawn as a hill and as a row of seats 0 to 6; seat i has children at 2i+1 and 2i+2 and its parent at (i-1)//2; seat 1 has children 3 and 4, seat 2 has children 5 and 6 0 1 2 3 4 5 6 0 1 2 3 4 5 6 children of i: 2i + 1 and 2i + 2 parent of i: (i - 1) // 2
The same hill, drawn as a tree and as an array. The top is always seat 0.

Seat 1's kids sit in seats 3 and 4; seat 2's kids sit in 5 and 6. The rule for the kids: double the seat number, then add one or add two. Going up is the opposite: take one off, halve it, drop any half. Seat 4: one off is 3, half is 1.5, drop the half, and the parent is seat 1. So no links are needed, just arithmetic.

Climb up, sink down

Play the waiting room step by step, with urgencies Emma 4, Jack 2, Tom 5, Kate 1.

  1. Add 4. Emma takes seat 0, the top.
  2. Add 2. Jack takes seat 1. His parent is seat 0, urgency 4. 2 is smaller, so swap: Jack is on top.
  3. Add 5. Tom takes seat 2. His parent is 2, and 5 is bigger, so he stays.
  4. Add 1. Kate takes seat 3. Her parent is seat 1, urgency 4: swap. Now her parent is seat 0, urgency 2: swap again. Kate is on top.
  5. Poll. Take the top, 1 (Kate). The last one, 4, jumps up to seat 0. Its children are 2 and 5; the smaller is 2, and 4 is bigger, so swap. Poll returns 1.
  6. Poll again. Take 2 (Jack). The last one, 5, jumps to the top. Its only child is 4; 5 is bigger, so swap. Poll returns 2.

Add sits at the end and climbs. Poll takes the top, lets the last one jump up, and it sinks. All four adds took just three swaps.

The code

class MinHeap:
    def __init__(self):
        self.a = [0] * 10
        self.size = 0

    def add(self, value):
        self.a[self.size] = value  # sit at the end
        i = self.size
        self.size += 1
        while i > 0 and self.a[i] < self.a[(i - 1) // 2]:
            i = self.swap(i, (i - 1) // 2)  # move up

    def poll(self):
        top = self.a[0]  # the most urgent
        self.size -= 1
        self.a[0] = self.a[self.size]  # last one jumps up
        i = 0
        while 2 * i + 1 < self.size:
            c = 2 * i + 1  # left child
            if c + 1 < self.size and self.a[c + 1] < self.a[c]:
                c += 1  # or right
            if self.a[i] <= self.a[c]:
                break  # in order
            i = self.swap(i, c)  # move down
        return top

    def swap(self, i, j):
        self.a[i], self.a[j] = self.a[j], self.a[i]
        return j

It's just a list (room for ten here) and a count. add is sift up: while the new value is smaller than its parent, swap and move up. poll is sift down: find the smaller child, and if the value is bigger, swap and move down until it's in order.

from min_heap import MinHeap

room = MinHeap()  # urgency 1 = most urgent
room.add(4)  # Emma
room.add(2)  # Jack
room.add(5)  # Tom
room.add(1)  # Kate
print("Next: urgency " + str(room.poll()))
print("Next: urgency " + str(room.poll()))
Next: urgency 1
Next: urgency 2

Kate arrived last but is called in first. Most urgent first, not first come.

Python's heapq

import heapq

room = []
heapq.heappush(room, (4, "Emma"))
heapq.heappush(room, (2, "Jack"))
heapq.heappush(room, (5, "Tom"))
heapq.heappush(room, (1, "Kate"))
while room:
    urgency, name = heapq.heappop(room)
    print("Next: " + name)
Next: Kate
Next: Jack
Next: Emma
Next: Tom

Python already has a heap. heapq keeps a plain list in heap order; each item is a tuple with the urgency first, so tuples compare by urgency. Same heap inside, now with names.

The longest trip, and the weak spot

In a room of seven, the hill is three levels tall. A newcomer with urgency 1 takes seat 7 and swaps three times, once per level, to reach the top: the longest climb there is. Take the top and the last patient jumps up and sinks at most two levels. But finding one particular patient (say, where is Tom?) is slow: the heap only orders parents over children, so you may check every seat.

Does a heap slow down when the room gets big? Every level has twice as many seats as the one above, so the hill grows wide quickly but tall slowly. Seven patients: three levels. A million patients: about twenty levels. One trip, at most about twenty swaps, instead of a million checks.

OperationCostWhy
Who is next (peek)O(1)always seat 0
AddO(log n)one trip up
Poll (take the top)O(log n)one trip down
Find one particular patientO(n)may check every seat
Plain list, find the smallestO(n)checks everyone, every time

Where you meet a heap

  • A task scheduler: the job with the highest priority runs next.
  • A route finder in a map app: the closest place not yet visited stays on top.
  • Timers and alarms: the one that rings soonest sits on top.
  • The top ten scores out of millions: keep ten in a heap with the weakest on top, so a new score only has to beat that one.

Try it yourself

Add a peek method to MinHeap that returns a[0] without removing it, and print who is next before you call poll.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Data Structures and Algorithms · 9 of 21

Previous
Tree Traversals: In-Order, Pre-Order and Post-Order as a Tour of the House
Next post
Graphs and Breadth-First Search (BFS): Fewest Hops, Level by Level

Related courses on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Data Structures and Algorithms Concepts: No Coding Needed

How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)

Related posts

What a Data Structure Is, and How Memory Works

Memory is a long row of numbered boxes, and opening any box is equally quick. A data structure is an agreed way of arranging things in those boxes, plus a few small notes. See with six songs on a phone why every structure is quick at some things and slow at others.

Arrays and Dynamic Arrays: Full? Get a Box Twice the Size

A fixed array never gets longer. A dynamic array fills its box, then copies everything into a box twice the size. Build one for Emma's playlist in Python, count the copies and shifts, and see why adding at the end stays cheap while inserting at the front costs almost 50 million shifts for 10,000 songs.

Linked Lists: A Chain of Clues, Built in Python

In a linked list every node holds a value and the address of the next node. Build a treasure hunt chain in Python: a new first clue is two moves at any size, slipping a clue in or out is just changing next, but reaching clue number i is a walk of i hops.

Stacks: Last In, First Out, With the Undo Button

A stack is last in, first out: the newest thing you put on is the first thing you take off. Build Emma's undo button in Python from a list and one top index, push, pop and peek in one step each, undo after a million edits, and see what happens when you pop an empty stack.

On this page

  • King of the hill
  • A hill in a row of seats
  • Climb up, sink down
  • The code
  • Python's heapq
  • The longest trip, and the weak spot
  • Where you meet a heap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related courses on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Data Structures and Algorithms Concepts: No Coding Needed

How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.