23. Task Scheduler
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
To schedule tasks with a cooldown period, I have used the following approach:
First, I determine the frequency of each task by iterating through the tasks
vector.
Then, I place the task frequencies into a priority queue (pq
) in descending order. This allows me to always pick the task with the highest frequency.
Next, I iterate until all tasks are completed. During each iteration, I find the task with the highest frequency from the pq
and remove it. If the task's frequency is greater than one, I calculate the time accordingly and store these remaining tasks in a vector named restTask
.
After processing all tasks from the pq
, I check if there are any remaining tasks. If there are remaining tasks, I place them back into the pq
and continue calculating time. Otherwise, I exit the loop.
Additionally, I check if there are incomplete tasks and if the cooldown time for the next task (k+1
th) has not been completed. In such cases, I add the idle time to our total time.
Time Complexity: O(N log N)
, where N
is the total number of tasks. It is due to the operations performed while iterating through the tasks and the priority queue.
Auxiliary Space Complexity: O(1)
since the space used by the priority queue and the vector restTask
does not scale with the input size.
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the repository.