← Back to DSA Animator
Task Scheduler LC #621 Medium Heap · Greedy Formula
Problem

You are given a list of CPU tasks labeled A–Z and an integer n representing a cooldown period. Between two tasks with the same label, the CPU must wait at least n intervals (idle counts). Return the minimum number of intervals to finish all tasks.

Example 1
Input: tasks = [A,A,A,B,B,B], n = 2
Output: 8
Explanation: A→B→idle→A→B→idle→A→B = 8 intervals.
Example 2
Input: tasks = [A,A,A,B,B,B], n = 0
Output: 6
Explanation: No cooldown — run all 6 tasks back-to-back.
Example 3
Input: tasks = [A,A,A,A,B,B,B,C,D], n = 2
Output: 10
Explanation: A appears 4×; formula gives (4-1)×3 + 1 = 10 with 2 idle slots.
Constraints: 1 ≤ tasks.length ≤ 10⁴  |  tasks[i] is uppercase A–Z  |  0 ≤ n ≤ 100
Try Examples
Custom:
Approach
Greedy: The most frequent task creates the skeleton with gaps of size n
Formula: max(tasks.length, (maxFreq-1)*(n+1) + maxCount)
Task Frequencies
Variables
maxFreq
maxCount
n (cooldown)
partCount
partLen
result
CPU Schedule Timeline
Most Frequent
Other Tasks
Idle
Tail
Formula Builder
1
maxFreq = highest task frequency
2
maxCount = tasks sharing maxFreq
3
partCount = maxFreq − 1
4
partLen = n + 1
5
emptySlots = partCount × partLen − (tasks − maxCount)
6
result = tasks.length + max(0, emptySlots)
Step Logic
Press ▶ Play or Next Step to begin the animation.
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Count task frequencies; find maxFreq (highest frequency)
2
maxCount = number of tasks sharing maxFreq
3
partCount = maxFreq − 1 partitions; partLen = n + 1 slots each
4
emptySlots = partCount × partLen − (tasks.length − maxCount)
5
return tasks.length + max(0, emptySlots)
Time
O(n)
Space
O(1)
Why the Formula Works

The most frequent task (say A with frequency f) forces a minimum structure: f−1 partitions of width n+1 separate its appearances, with the final chunk appended at the end. Other tasks slot into the partitions; any leftover partition capacity becomes idle time. If there are enough tasks to fill everything, idle = 0 and the answer is simply tasks.length. Ties at maxFreq share the final tail.