Task Scheduler
The problem
You are given a list of tasks represented by uppercase English letters ('A' to 'Z'), and an integer n representing a cooldown interval between two same tasks.
Each task takes exactly 1 CPU interval to complete. Tasks can be executed in any order, but identical tasks must be separated by at least n intervals, during which the CPU may remain idle or execute other tasks.
Return the minimum number of **CPU **intervals required to complete all the tasks.
Input: tasks = ["A","A","A","B","B","B"], n = 2 **Output: **8 Explanation:
- One valid execution order is:
- A -> B -> idle -> A -> B -> idle -> A -> B
- Total intervals = 8
Input: tasks = ["A","C","A","B","D","B"], n = 1 Output: 6 Explanation:
- A possible execution:
- A -> B -> C -> D -> A -> B
- No idle interval is needed as cooldown = 1.
Input: tasks = ["A","A","A","B","B","B"], n = 3
- 1 <= tasks.length <= 104
- tasks[i] is an uppercase English letter from 'A' to 'Z'
- 0 <= n <= 100
cpp
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
// Your code goes here
}
};java
class Solution {
public int leastInterval(char[] tasks, int n) {
// Your code goes here
}
}python
class Solution:
def leastInterval(self, tasks, n):
# Your code goes herejavascript
class Solution {
leastInterval(tasks, n) {
// Your code goes here
}
}csharp
class Solution {
public int LeastInterval(char[] tasks, int n) {
// Your code goes here
}
}go
func leastInterval(tasks []byte, n int) int {
// Your code goes here
}Stuck? Show a way to structure it+
- 01Count task frequencies and find the maximum count.
- 02Compute the required cooldown frame around max-frequency tasks.
- 03Account for how many task types share that maximum.
- 04Take the maximum of frame length and task count.
Reference answer
Then expect these follow-ups
How would you output an actual schedule?
Tests: heap simulation
What changes with different task durations?
Tests: general scheduling
Free to read · better with Enzo
Practice this out loud with Enzo
Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.
Next question