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
Hiring now
Google has 52 open roles right now
landed applies to roles like these for you, on each company’s own site, with answers written for the role.
Small Business Field Sales Representative
Denver, Colorado
Senior Technical Program Manager, Special Projects
Denver, Colorado; Lakewood, Colorado, United States
OSP Engineering Lead, Technical Operations
Denver, Colorado
Next question