~/problems / Heaps / Heap scheduling (deadlines, leases)

Task Scheduler

medium ~25 min

A CPU runs one unit-length job per time slot, or sits idle. You get a list of jobs labelled with uppercase letters ("A"–"Z"), in any order, and a cooldown n: after running a job with some label, at least n slots must pass before another job with the same label can run. Jobs can be run in any order.

Write least_interval(tasks, n) that returns the minimum number of slots (busy plus idle) needed to finish every job.

least_interval(["A", "A", "B"], 2)             # 4   A B _ A
least_interval(["A", "A", "A", "B", "B"], 1)   # 5   A B A B A
least_interval(["A", "B", "C", "A"], 0)        # 4
least_interval(["X", "X", "X"], 3)             # 9   X _ _ _ X _ _ _ X

Constraints: up to 250,000 jobs, 0 <= n <= 100.

Simulating slot by slot works, but the idle slots can run into the millions (think 100,000 copies of one label with n = 100), so the tests expect an answer computed from the label counts in O(len(tasks)).

Show hint

think about the most frequent label: its copies split the timeline into frames of length n + 1. Then ask how many labels share that top count, and remember the answer can never be smaller than len(tasks).

Topic: Heap scheduling (deadlines, leases). Min-heap of deadlines, lazy deletion, event simulation.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc