Module 09 of 12

Heaps & Priority Queues

Lessons

About This Module

A priority queue answers one question extremely well: "what is the most important item right now?" Unlike an ordinary queue, which returns items in the order they arrived, a priority queue always returns the item with the highest priority first. Task schedulers, emergency rooms and shortest-path algorithms all work this way, and the standard way to build one is a heap.

This module starts with what a priority queue is and how a binary heap implements it: a complete binary tree, stored in an array, where the smallest value (min heap) or the largest (max heap) always sits at the root. Inserting and removing the top item take O(log n), while reading it takes O(1).

The second half is about building and using heaps. Heapify turns an unordered array into a heap, and it is also the core step of heap sort. The Kth Largest Element problem then shows the most common use: keep a heap of size k so you never have to sort everything. Watch the lessons in order, then continue on to Graphs.

Lessons

4 videos
01

Introduction to Priority Queue and Heap Data Structure

An introduction to the priority queue and the heap using a real-life scenario, and why this structure has so many uses.

02

Heaps Visually Explained (Priority Queues)

How a heap works, shown with a visual max heap, including insertion, deletion and building a heap.

03

Heapify and Build Heap Animation

An animation of how heapify and build heap work, walking through the algorithm step by step.

04

Kth Largest Element in an Array: Heap of Size K (LeetCode 215)

A Python heap solution to LeetCode 215 that keeps a heap of at most k elements, a good practice problem for the heap operations.