AlgoMaster Logo

Task Scheduler

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Greedy Scheduling with Priority Queue

Intuition:

The problem can be visualized as filling slots in a schedule but ensuring that there are enough cooldown periods between the same tasks. The most basic approach involves using a priority queue to always schedule the task that is left with the highest frequency. This strategy simulates the task execution by tracking time and rearranging tasks based on cooldowns.

  1. Frequency Counting: First, calculate the frequency of each task.
  2. Priority Queue: Use a max heap (priority queue) to always schedule the most frequent task available, as this task contributes the most to minimizing the idle intervals.
  3. Cooldown Management: Use a cooldown queue to track tasks that are in cooldown periods and need to be paused before they can be scheduled again.
  4. Time Simulation: Iterate over time units and use steps 2 and 3 above to decide what task, if any, to execute at each time step.

Code:

2. Greedy Scheduling with Frequency Calculations

Intuition:

The most optimal solution to this problem is to directly calculate the least interval based on the required cooling periods and the frequencies of the most often appearing tasks. We can use a mathematical approach to determine how to place the tasks efficiently.

  1. Find Maximum Frequency: Determine the maximum frequency tasks need to be repeated.
  2. Slots Calculation: Calculate the possible slots needed to place the most frequent tasks and any additional tasks that fit in the gaps.
  3. Calculate Idle Units: Calculate exactly how many idle units are needed after placing other tasks between the maximum frequency tasks.
  4. Total Time Calculation: Determine the total required time by summing filled slots and idle time.

Code: