Advanced Topics in Computer Science

Unit 7: Heaps and Heap Sort

Students study priority queues and the heap structure that supports efficient access to the highest or lowest priority item.

Unit Focus

What this unit is really teaching

This unit connects tree ideas to array-based implementation and prepares students for scheduling, graph algorithms, and heapsort.

Key Topics

  • +Complete binary trees and array representation
  • +Min-heaps, max-heaps, heap order, and structural invariants
  • +Insert, remove, peek, percolate up, and percolate down
  • +PriorityQueue use cases and custom comparators
  • +Heapify and heapsort
  • +Runtime comparison with sorted arrays, linked lists, and binary search trees

Practice Work

Implementation and analysis tasks

Student task

Implement a binary heap-backed priority queue.

Student task

Use a priority queue to simulate task scheduling or emergency triage.

DSA Assignment Bank

30 interview-style algorithm questions for this unit

Code Scholars provides structured assignments, implementation support, edge-case review, and runtime analysis coaching so students learn the concept rather than only memorizing a solution.

1

Min-heap of fixed size

Find top k scores

Maintain a heap of size k while scanning scores so the final heap contains the k largest values.

2

Priority queue merge

Merge sorted streams

Use a priority queue to merge several sorted lists by repeatedly taking the smallest current value.

3

Two heaps

Track running median

Use a max-heap for the lower half and a min-heap for the upper half to report the median after each insertion.

4

Heap plus queue

Schedule tasks by cooldown

Arrange repeated tasks so identical tasks are separated by a cooldown, using counts and waiting times.

5

Heap or selection

Find k closest points

Return the k points closest to a center point and compare max-heap and sorting approaches.

6

Priority queue comparator

Simulate emergency triage

Order patients by severity, arrival time, and name, then explain comparator tie behavior.

7

Greedy heap

Minimize rope combination cost

Repeatedly combine the two smallest lengths and prove why the heap supports the greedy choice efficiently.

8

Fixed-size heap

Find kth largest in a stream

Process values one at a time and report the kth largest value after each update.

9

Bottom-up heap construction

Heapify an array

Transform an array into a heap using percolate-down from the last internal node.

10

Percolate up

Trace heap insertion

Insert values into a binary heap and show the array after each percolate-up step.

11

Percolate down

Trace heap removal

Remove the root, move the last value to the root, and show each swap needed to restore heap order.

12

Heap sort phases

Implement heapsort

Build a max-heap, repeatedly move the max to the end, and restore heap order in the remaining prefix.

13

Priority queue window

Find smallest range across lists

Choose one value from each sorted list so the range is as small as possible.

14

Min-heap by end time

Assign rooms to meetings

Given meeting intervals, compute the minimum number of rooms needed by tracking earliest ending meetings.

15

Max-heap by frequency

Reorganize a string

Rearrange characters so no adjacent characters match, or explain why it is impossible.

16

Comparator design

Choose a heap comparator

Create a comparator for assignments ordered by due date, priority, and student name.

17

Data structure tradeoff

Compare heap with sorted list

Explain which structure is better for frequent insertions with repeated highest-priority removals.

18

Priority queue frontier

Use heap for Dijkstra-style search

Maintain frontier nodes ordered by best known distance and skip stale entries safely.

19

Heap for k-sorted data

Find almost sorted output

Sort data where each item is at most k positions from its correct location.

20

Min-heap by time

Process delayed notifications

Simulate sending notifications by always processing the earliest scheduled event first.

21

Array representation

Debug broken heap indexes

Given parent and child index formulas, find the off-by-one error in a heap implementation.

22

Structural invariant

Validate heap order

Check whether an array satisfies min-heap order and explain why completeness is implicit in array storage.

23

Heap encapsulation

Implement custom priority queue API

Build offer, poll, peek, size, and isEmpty while hiding the internal array representation.

24

Heap with visited pairs

Find largest pair sums

Given two sorted arrays, find the largest k pair sums without generating every pair.

25

Greedy min-heap

Balance project workloads

Assign each new task to the currently least-loaded student team and analyze when this greedy plan is reasonable.

26

Runtime analysis

Count heap operations

Given n inserts and m removals, compute the total asymptotic cost and compare with repeated sorting.

27

Heap plus lazy deletion

Design a leaderboard with updates

Support changing player scores while avoiding incorrect stale heap entries.

28

Discrete event simulation

Use a heap for event simulation

Process simulation events ordered by time and add future events as the simulation runs.

29

DSA decision

Select data structure for priorities

Choose between queue, sorted ArrayList, TreeMap, and heap for several priority-based scenarios.

30

DSA support

Plan a heaps assignment

Create a heap assignment requiring manual traces, implementation, comparator design, and runtime comparison.

Need support with Unit 7?

Work through the concepts, code, edge cases, and runtime analysis with 1:1 guidance.