KatInterview

Task Scheduler with Cooldown Periods

Greedy & IntervalsAuto-graded · 21 test cases
MediumAuto-gradedGreedy & Intervalsgreedyfrequency-countingscheduling

Last updated

Tests greedy scheduling with frequency counting to compute minimum execution time under per-task-type cooldown constraints.

You have a single-processor system that must execute a list of tasks. Each task is identified by an uppercase letter from 'A' to 'Z' in the array tasks. Tasks with the same letter represent the same task type, and each task takes exactly one time unit to complete.

There is a cooldown period represented by a non-negative integer n. After executing a task of a particular type, the processor must wait at least n time units before executing another task of that same type. During the cooldown, the processor can either execute a task of a different type or remain idle.

The processor executes exactly one task or remains idle for exactly one time unit in each cycle. You may schedule the tasks in any order you choose.

Return the minimum total time units required to complete all tasks.

Constraints:

  • 1 <= tasks.length <= 10^4
  • tasks[i] is an uppercase English letter from 'A' to 'Z'
  • 0 <= n <= 100

Examples

Example 1

Input: min_schedule_time(['A', 'A', 'A', 'B', 'B', 'B'], 2)

Output: 8

Example 2

Input: min_schedule_time(['A', 'A', 'A', 'B', 'B', 'B'], 0)

Output: 6

Example 3

Input: min_schedule_time(['A', 'A', 'A', 'A', 'A', 'A', 'B', 'C', 'D', 'E', 'F', 'G'], 2)

Output: 16

Hints

Hint 1

The most frequent task type determines the minimum schedule length. Think about how many 'slots' you need between its occurrences.

Hint 2

Build a conceptual frame: place the most frequent task with exactly n slots between each occurrence. How many frames do you create?

Hint 3

If multiple task types share the maximum frequency, they all need a position in the final segment. Count how many tie for first place.