Given a characters array tasks representing the tasks a CPU needs to do, and a cooldown integer n, each task takes 1 CPU interval. Identical tasks must be separated by at least n cooldown intervals.
Most people simulate this using a Max-Heap and a cooldown queue, ticking clock cycles one by one. But there is a closed-form O(1) mathematical formula that calculates the minimum intervals directly without simulating a single cycle. How is that formula derived?
The Task Scheduler problem is a masterclass in recognizing that the most frequent task dictates the entire schedule structure.
1. Deriving the Formula Visually
Suppose our tasks are
[A, A, A, B, B, C]with cooldownn = 2.Task
Aappears most frequently ($count = 3$). Between eachA, there must be at leastn = 2cooldown slots:Notice the structure:
max_freq - 1full frames.n + 1(the task itself plus itsncooldown slots).2. The Closed-Form Equation
Let
max_freqbe the highest frequency of any task, andmax_countbe how many tasks tie for that highest frequency (for example, if both A and B appear 3 times,max_count = 2).What if there are so many other tasks that no CPU idle slots are needed?
If you have tons of diverse tasks (e.g.
[A, A, B, B, C, D, E, F, G, H]), they easily fill up all idle slots, and the CPU never needs to idle at all! In that case, the answer is simplylen(tasks).Therefore, the global answer is simply:
Clean Python 3.12 Implementation (0 CPU Simulation Cycles!)
Complexity Breakdown
O(N)to count task frequencies. The mathematical formula itself evaluates inO(1)time!O(1)auxiliary space, because the alphabet size is bounded by 26 English uppercase letters.Here is the C++20 Closed-Form Math implementation for Task Scheduler. It eliminates all simulation loops and runs in
O(N)time andO(1)space.Complexity:
O(N)time to tally frequencies andO(1)space using a fixed 26-element array.