Task Scheduler - Problem
๐ฏ CPU Task Scheduler
Imagine you're managing a CPU scheduler that needs to execute tasks efficiently while respecting cooling periods between similar operations. You have an array of tasks, each labeled with a letter from
Here's the challenge: identical tasks must be separated by at least
โข Execute one task, OR
โข Remain idle (cooling down)
Your mission: Find the minimum number of intervals needed to complete all tasks.
Example: Tasks =
Optimal schedule:
Total intervals: 8
Imagine you're managing a CPU scheduler that needs to execute tasks efficiently while respecting cooling periods between similar operations. You have an array of tasks, each labeled with a letter from
A to Z, and a cooldown number n.Here's the challenge: identical tasks must be separated by at least
n intervals. During each interval, the CPU can either:โข Execute one task, OR
โข Remain idle (cooling down)
Your mission: Find the minimum number of intervals needed to complete all tasks.
Example: Tasks =
["A","A","A","B","B","B"], n = 2Optimal schedule:
A โ B โ idle โ A โ B โ idle โ A โ BTotal intervals: 8
Input & Output
example_1.py โ Basic Case
$
Input:
tasks = ["A","A","A","B","B","B"], n = 2
โบ
Output:
8
๐ก Note:
Optimal schedule: A -> B -> idle -> A -> B -> idle -> A -> B. The cooldown period forces idle time between identical tasks.
example_2.py โ No Cooldown
$
Input:
tasks = ["A","A","A","B","B","B"], n = 0
โบ
Output:
6
๐ก Note:
With no cooldown required, all tasks can be executed consecutively in any order.
example_3.py โ Diverse Tasks
$
Input:
tasks = ["A","A","A","A","A","A","B","C","D","E","F","G"], n = 2
โบ
Output:
16
๐ก Note:
Task A appears 6 times, creating the framework. Other tasks fill the cooling periods: A->B->C->A->D->E->A->F->G->A->B->C->A->D->E->A.
Visualization
Tap to expand
Understanding the Visualization
1
Inventory Count
Count how many items each machine type needs to process
2
Bottleneck Analysis
Identify the machine type with the most work (highest frequency)
3
Framework Design
The busiest machine creates time slots with cooling periods
4
Optimization
Other machines can work during cooling periods of the busiest machine
Key Takeaway
๐ฏ Key Insight: The most frequent task type creates the scheduling framework - other tasks can fill the cooling periods, making the solution mathematically predictable!
Time & Space Complexity
Time Complexity
O(m)
Single pass to count tasks, O(26) to find max frequency
โ Linear Growth
Space Complexity
O(1)
Only need to store 26 task counters (constant space)
โ Linear Space
Constraints
- 1 โค tasks.length โค 104
- tasks[i] is an uppercase English letter
- 0 โค n โค 100
- The number of unique tasks is at most 26
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code