23. Task Scheduler
The problem can be found at the following link: Question Link
My Approach
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 namedrestTask
.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 thepq
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 and Auxiliary Space Complexity
Time Complexity:
O(N log N)
, whereN
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 vectorrestTask
does not scale with the input size.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. 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 getlost01/gfg-potd repository.
Last updated