Introduction
The Task Scheduler problem involves scheduling tasks while maintaining a cooldown period.
Given:
- list of tasks
- cooldown time n
Rules:
- same task must wait n intervals
before executing again - CPU can stay idle if needed
The task is to:
- find minimum intervals required
to complete all tasks
This problem is one of the most important applications of:
Greedy + Queue + Max HeapThis problem helps in understanding:
- task scheduling
- greedy optimization
- heap processing
- cooldown simulation
Example
Input:tasks =["A","A","A","B","B","B"] n = 2
Output: 8
Explanation:
Schedule: A → B → idle
→ A → B → idle
→ A → B
Total intervals: 8
Constraints
1 <= tasks.length <= 10^4tasks[i] is uppercase English letter
0 <= n <= 100Approach 1 : Brute Force Simulation
Explanation
The simplest way is:
- Simulate every interval
- Pick available task
- Track cooldown manually
This works but repeated scanning becomes inefficient.
Steps
- Count task frequencies.
- Simulate intervals.
- Execute valid task.
- Track cooldown time.
- Continue until all tasks finish.
Dry Run
Tasks:A A A B B B
Cooldown: 2
Schedule:
A B idle
A B idle
A B
Intervals: 8
Brute Force Code
Complexity Analysis
Time Complexity: O(n²)Explanation:Tasks are repeatedly scanned.
Space Complexity: O(1) Explanation:
Only fixed alphabet tasks are stored.
Approach 2 : Greedy + Max Heap
Explanation
The optimized solution uses:
Max Heap + QueueIdea:
- always execute task
with highest remaining frequency - cooldown queue stores:
- tasks waiting to re-enter heap
Process:
- Pick highest frequency task
- Execute it
- Push into cooldown
- Reinsert after cooldown expires
This minimizes idle intervals.
Steps
- Count task frequencies.
- Insert into max heap.
- Execute highest frequency task.
- Push task into cooldown queue.
- Reinsert after cooldown.
- Count total intervals.
Dry Run
Tasks:A A A B B B
Heap:
A:3
B:3
Execute:
A
Cooldown: A waiting
Execute: B
Cooldown: A,B waiting Idle interval occurs
Continue process...
Final Answer: 8
Greedy + Max Heap Code
Complexity Analysis
Time Complexity: O(n log n)Explanation:Heap insertion and removal are performed repeatedly.
Space Complexity: O(1) Explanation:
Only fixed alphabet tasks are stored.
Edge Cases