Solution: Task Scheduler
Let's solve the Task Scheduler problem using the Merge Intervals pattern.
We'll cover the following
Statement#
We’re given a character array, tasks, where each character represents a unique task. These tasks need to be performed by a single CPU, with each task taking one unit of time. The tasks can be performed in any order. At any given time, a CPU can either perform some task or stay idle.
For the given tasks, we are also provided with a positive integer value, n, which represents the cooling period between any two identical tasks. This means that the CPU must wait for at least n units of time before it performs the same task again. For example, if we have the tasks n = 2, then after performing the first
Given the two input values, tasks and n, find the least number of units of time the CPU will take to perform the given tasks.
Constraints:
tasks.lengthtasksconsists of uppercase English letters.n
Solution#
The optimal strategy is to schedule the most frequent task first, then the second most frequent task, and so on. This is because once we’ve scheduled the most frequent task, we can get an estimate of the maximum idle time. Therefore, we keep track of the frequencies of all tasks using a hash map, frequencies. Let’s say we have tasks = n = 2, then frequencies =
Next, we utilize these idle slots to schedule the remaining tasks. The next most frequent task is
Finally, we can schedule task tasks = n = 2.
The formula above works fine as long as
For example, tasks = n =
In general, the total time required by the CPU can be calculated as:
Let’s look at the following illustration to get a better understanding of the solution:
1 of 8
2 of 8
3 of 8
4 of 8
5 of 8
6 of 8
7 of 8
8 of 8
Let’s take a look at the code for the algorithm we just discussed.
Time complexity#
Counting the frequencies of tasks by iterating over the task list takes
Space complexity#
Because the tasks are represented by uppercase English letters, we can have a maximum of
Task Scheduler
Insert Interval