Skip to lesson

Scheduling with heaps

Priority queues manage execution timelines in task scheduling, resource allocation, and meeting room reservation systems.

Meeting rooms allocation using a min heap

Given meeting intervals with start and end times, we must find the minimum conference rooms needed. A brute-force check tests all pairs of meetings for time collisions, requiring quadratic O(n^2) comparisons. Alternatively, scanning every minute on a timeline depends heavily on wide timestamp ranges.

Example 1 · Brute force: compare every pair, O(n^2) time, O(1) space

Main.javaJava
public class Main {    public static void main(String[] args) {        int[][] meetings = {{0, 30}, {5, 10}, {15, 20}, {25, 40}};        int rooms = 0;        for (int[] a : meetings) {            int running = 0;            for (int[] b : meetings) {                if (b[0] <= a[0] && a[0] < b[1]) running++;   // b is still running when a starts            }            rooms = Math.max(rooms, running);        }        System.out.println("Rooms needed: " + rooms);    }}
Output
Rooms needed: 2

What this code does

  • For each meeting the inner loop counts how many meetings are running at its start time.
  • The largest count is the number of rooms needed at the busiest moment.
  • Two nested loops over n meetings give n * n comparisons.

Example 2 · Optimal: sort + min-heap of end times, O(n log n) time, O(n) space

Main.javaJava
import java.util.Arrays;import java.util.Comparator;import java.util.PriorityQueue;
public class Main {    static int minMeetingRooms(int[][] intervals) {        if (intervals == null || intervals.length == 0) return 0;        Arrays.sort(intervals, Comparator.comparingInt(a -> a[0]));
        PriorityQueue<Integer> endTimes = new PriorityQueue<>();        for (int[] m : intervals) {            if (!endTimes.isEmpty() && endTimes.peek() <= m[0]) {                endTimes.poll();            }            endTimes.offer(m[1]);        }        return endTimes.size();    }
    public static void main(String[] args) {        int[][] meetings = {{0, 30}, {5, 10}, {15, 20}};        System.out.println("Rooms needed: " + minMeetingRooms(meetings));    }}
Output
Rooms needed: 2

What this code does

  • Meetings are sorted by start times: [0,30], [5,10], [15,20].
  • Meeting [5,10] overlaps with [0,30], allocating a second room.
  • Meeting [15,20] reuses the room freed by [5,10] at time 10.
  • It is faster because the heap root tells at once which room frees first, so no meeting is compared against all the others.

We solve this in O(n log n) by combining interval sorting with a min-heap. First, sort all meeting intervals by start time in ascending order. Next, maintain a min-heap storing the end times of meetings currently occupying rooms. When evaluating a new meeting starting at time S, inspect the heap root peek value. If the earliest meeting end time is less than or equal to S, that room is freed. Poll the finished meeting end time from the heap to reuse the room. Otherwise, no room is free, requiring a new room allocation. Push the current meeting's end time into the heap. The final heap size equals the minimum number of rooms required.

Predict the output

Predict the heap

Read each snippet and pick what it prints.

Round 1 of 2

PriorityQueue<Integer> ends = new PriorityQueue<>();
ends.offer(30);
ends.offer(10);
ends.offer(20);
System.out.println(ends.peek());

Task scheduler with cooldown periods

A CPU task scheduler executes a list of tasks with a cooldown constraint n between identical tasks. During cooldown intervals, the CPU must either run different tasks or remain idle. A greedy strategy always prioritizes executing the most frequent remaining tasks first.

Example 3 · Task Scheduler Simulation

Main.javaJava
import java.util.*;
public class Main {    static int leastInterval(char[] tasks, int n) {        int[] counts = new int[26];        for (char c : tasks) counts[c - 'A']++;
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());        for (int cnt : counts) {            if (cnt > 0) maxHeap.offer(cnt);        }
        int time = 0;        while (!maxHeap.isEmpty()) {            List<Integer> temp = new ArrayList<>();            for (int i = 0; i <= n; i++) {                if (!maxHeap.isEmpty()) {                    temp.add(maxHeap.poll());                }            }
            for (int cnt : temp) {                if (cnt - 1 > 0) maxHeap.offer(cnt - 1);            }
            time += maxHeap.isEmpty() ? temp.size() : n + 1;        }        return time;    }
    public static void main(String[] args) {        char[] tasks = {'A', 'A', 'A', 'B', 'B', 'B'};        System.out.println("Least intervals (n=2): " + leastInterval(tasks, 2));    }}
Output
Least intervals (n=2): 8

What this code does

  • Tasks execute in cycles of length n + 1 = 3.
  • Order: A, B, idle, A, B, idle, A, B takes 8 intervals.
  • Max-heap greedily schedules highest frequency tasks first.

We count task frequencies with a map and place positive counts into a max-heap. In each cycle of length n + 1, poll up to n + 1 tasks from the max-heap. Decrement each polled count by one and store tasks with positive remaining counts temporarily. After completing the cycle, push all non-zero tasks back into the max-heap. If the heap is still not empty, add n + 1 intervals to total elapsed time. If the heap becomes empty, only add the actual count of tasks processed in that final round.

Real world job schedulers and event loops

Operating systems schedule background threads using priority queues to prevent starvation. Linux Completely Fair Scheduler uses virtual runtime heaps to distribute CPU cores evenly.

Example 4 · Earliest Deadline First Job Scheduler

Main.javaJava
import java.util.Comparator;import java.util.PriorityQueue;
public class Main {    static class Job {        String name;        int deadline;        Job(String name, int deadline) {            this.name = name;            this.deadline = deadline;        }    }
    public static void main(String[] args) {        PriorityQueue<Job> edfQueue = new PriorityQueue<>(Comparator.comparingInt(j -> j.deadline));        edfQueue.offer(new Job("Backup", 500));        edfQueue.offer(new Job("RenderFrame", 100));        edfQueue.offer(new Job("SendEmail", 250));
        while (!edfQueue.isEmpty()) {            Job j = edfQueue.poll();            System.out.println("Executing " + j.name + " (Deadline: " + j.deadline + ")");        }    }}
Output
Executing RenderFrame (Deadline: 100)
Executing SendEmail (Deadline: 250)
Executing Backup (Deadline: 500)

What this code does

  • Jobs are ordered by earliest deadline using a min-heap.
  • The most urgent task RenderFrame runs first.
  • All jobs execute in ascending deadline sequence.

The Node.js runtime and browser event loops schedule timers using a min-heap in libuv. When timers are created with setTimeout, their target timestamps enter a min-heap. The event loop peeks at the heap root to sleep until the next timer expires. Cloud orchestrators like Kubernetes schedule batch compute pods based on priority and deadlines.

Next step

Check your understanding

10 quick questions