Tags

Heap

Heap

1 lesson
14 problems
4 code snippets
1 question bank
7 community items

heap

Data Structures

1 lesson

Heaps & Priority Queue

Intermediate

55 min

2 prereqs

Pull the next task in priority order from a stream of millions, and a sorted array gives you `O(1)` extract but `O(n)` insert; a sorted linked list flips the costs but stays linear; a balanced BST hits `O(log n)` for both but with substantial pointer overhead. A **Heap** quietly outperforms all three for this exact workload by storing a complete binary tree in a flat array and keeping just the min (or max) at the root. This lesson covers the heap property, the parent-and-child index formulas (`parent = (i-1)/2`, `left = 2i+1`, `right = 2i+2`) that let array indices encode tree structure with no pointers, sift-up and sift-down for `O(log n)` insert and extract, and the linear-time `heapify` build. You will see how this maps onto the priority queue abstraction and onto interview staples such as top-K elements, K-th largest, merge K sorted lists, and the streaming median with two heaps; on the systems side, the same structure powers Dijkstra and Prim. In **Trees: Binary Tree Fundamentals**, you saw what a complete binary tree is and how to traverse one; the heap reuses that exact shape but stores it implicitly. **Arrays & Strings** is what makes the implicit storage cheap: a flat array gives `O(1)` parent and child access through arithmetic, with no allocations per node. Next, **Binary Search Tree (BST)** trades the heap's partial ordering for a full ordering invariant, unlocking sorted iteration and key-based search at the cost of needing actual pointers.

Not Started

0%

Heap
Priority Queue
Min Heap
Max Heap
Heapify
Data Structures
Intermediate
Premium
Trees
Binary Tree

Practice Problems

14 problems

Kth Largest Element in a Stream

Free
Not Started
Easy

Design a class that finds the kth largest element in a stream of numbers using a min-heap.

Heap
Min Heap
Priority Queue
Data Structures
Beginner

350

5

Last Stone Weight

Free
Not Started
Easy

Simulate smashing the two heaviest stones together repeatedly using a max-heap and return the weight of the last remaining stone.

Heap
Max Heap
Priority Queue
Simulation
Beginner

187

5

Find Median from Data Stream

Free
Not Started
Hard

Design a data structure that efficiently finds the median from a stream of integers using two heaps.

Heap
Min Heap
Max Heap
Priority Queue
Median Finding
Data Structures
Advanced

712

5

Merge k Sorted Lists

Free
Not Started
Hard

Merge k sorted linked lists into one sorted linked list using a divide-and-conquer or min-heap approach.

Singly Linked List
Heap
Divide and Conquer
Advanced

1.1k

28

Minimum Interval to Include Each Query

Not Started
Hard

Given a list of intervals and a list of queries, for each query find the size of the smallest interval that contains it, or -1 if no interval contains it.

Algorithms
Advanced
Sorting
Sweep Line
Heap
Interval Problems
Premium

1.1k

31

Swim in Rising Water

Not Started
Hard

Given an n x n grid of elevations, find the minimum time t at which you can swim from the top-left to the bottom-right corner.

Graphs
BFS
Binary Search
Heap
Shortest Path
Advanced

691

15

Design Twitter

Free
Not Started
Medium

Design a simplified Twitter with post, follow/unfollow, and a news feed that merges recent tweets from followed users using a heap.

Heap
Min Heap
Priority Queue
Hash Map / Dictionary
Data Structures
Intermediate

638

11

IPO

Free
Not Started
Medium

Maximize capital after completing at most k projects by greedily selecting the most profitable affordable projects using a max-heap.

Heap
Max Heap
Priority Queue
Greedy
Sorting
Intermediate

285

2

K Closest Points to Origin

Free
Not Started
Medium

Find the k closest points to the origin using a max-heap to efficiently track the k smallest distances.

Heap
Max Heap
Priority Queue
Sorting
Intermediate

429

10

Find K Pairs with Smallest Sums

Free
Not Started
Medium

Given two sorted arrays, find the k pairs with the smallest sums using a min-heap to efficiently explore candidates.

Heap
Min Heap
Priority Queue
Sorting
Intermediate

696

12

Kth Largest Element in an Array

Free
Not Started
Medium

Find the kth largest element in an unsorted array using a min-heap or quickselect algorithm.

Heap
Min Heap
Priority Queue
Quickselect
Sorting
Intermediate

485

2

Meeting Rooms II

Not Started
Medium

Given an array of meeting time intervals, determine the minimum number of conference rooms required to hold all meetings.

Algorithms
Intermediate
Greedy
Sorting
Sweep Line
Heap
Interval Problems
Meeting Rooms
Premium

1k

7

Network Delay Time

Not Started
Medium

Given a network of n nodes and weighted directed edges representing signal travel times, find the time it takes for a signal sent from node k to reach all nodes.

Graphs
Dijkstra's Algorithm
Shortest Path
Weighted Graphs
Directed Graphs
Heap
Intermediate

1k

24

Task Scheduler

Free
Not Started
Medium

Determine the minimum number of intervals needed to execute all tasks given a cooldown period between identical tasks.

Heap
Max Heap
Priority Queue
Greedy
Frequency Count
Intermediate

745

11

Code Snippets

4 snippets
Code Snippet

Min-Heap Template

JavaScript still has no built-in priority queue, so most real-world code rolls its own min-heap. This snippet covers a generic comparator-based heap with push and pop, the sift-up and sift-down internals that make both O(log n), and a heapify-from-array helper that builds a heap from an arbitrary input in O(n).

JavaScript
data-structures
heap
code-template
algorithms

588

5

Medium
Code Snippet
Premium

Dijkstra Shortest Path Template

Dijkstra's algorithm finds the shortest path from a source to every reachable node in a weighted graph with non-negative edge weights. The textbook O((V + E) log V) implementation pairs a min-heap with a relaxation loop. This snippet covers the heap-based template, a parent-tracking variant that reconstructs the actual path, and an early-exit form for single-target queries.

JavaScript
algorithms
dijkstra
code-template
heap

1.1k

17

Hard
Code Snippet

heapq Min-Heap Recipes

Python's `heapq` module turns any list into a binary min-heap in place, supporting O(log n) push and pop. It is the priority-queue primitive that powers Dijkstra, Top-K, and merging sorted streams. This snippet covers the basic push and pop, the Top-K largest pattern using `nsmallest` and `nlargest`, and the merge of multiple sorted iterables in O(N log K).

Python
py-standard-library
heap
code-template
algorithms

586

17

Medium
Code Snippet

Min-Heap via std::priority_queue

`std::priority_queue` is a max-heap by default. To get a min-heap you flip the comparator. This snippet shows the three common forms: a min-heap of ints with `std::greater`, a min-heap of pairs sorting by first element, and a custom comparator over a struct for things like Dijkstra. All run in O(log n) per push/pop.

C++
cpp-stl
priority-queue
min-heap
heap

1.1k

35

Medium

Community

7 items
Problem
Medium
Free

Furthest Building You Can Reach

Use bricks for short climbs and ladders for tall ones, swapping greedily to maximize reach.

heap
priority-queue
greedy

470

2

4.3 (14)

Apr 20, 2026

by @davidtoure

Problem
Medium
Free

Top K Frequent Words

Return the k most frequent words, breaking frequency ties alphabetically and returning results in descending frequency.

heap
priority-queue
hash-table
sorting

262

8

4.5 (15)

Apr 18, 2026

by CodeSnatch

Problem
Medium
$6.99

Reorganize String

Rearrange a string so no two adjacent characters are equal, or report that no rearrangement exists.

heap
priority-queue
greedy
strings

385

9

4.3 (9)

Mar 27, 2026

by @oliviafoster

Problem
Medium
$10.00

Top K Frequent Elements

Return the k most frequent elements in O(n) time using bucket sort by frequency. A staple of mid-level interview rotations.

hash-map
bucket-sort
heap
interview-prep

996

23

3.8 (41)

Mar 24, 2026

by @ezb1981

Article

Heaps and Priority Queues: When the Order Matters

Why a binary heap is the right shape for top-K, Dijkstra, k-way merge, and scheduling, plus the one trap I have hit twice with mutable heap entries.

heap
priority-queue
data-structures
min-heap
interview-prep

346

1

4.3 (9)

Mar 20, 2026

by @leoeriksson

Problem
Medium
Free

Path with Maximum Probability

Find the path between two nodes that maximizes the product of edge success probabilities, via modified Dijkstra.

graphs
dijkstra
shortest-path
heap

1k

31

4.2 (9)

Feb 28, 2026

by @owentanaka

Problem
Hard
$8.99

Minimum Number of Refueling Stops

Reach the target with the fewest refueling stops, deferring fuel choices via a max-heap of passed stations.

heap
priority-queue
greedy

404

2

4.5 (11)

Nov 24, 2025

by @hanaokoro