Problem 481293 · medium · Level 04 Non-Linear Data Structures

CPU Cooldown Schedule

heaps · greedy · scheduling · counting

A CPU must run a list of tasks, each a single uppercase letter naming its type, one task per time slot in any order. After running a task of some type, the CPU must wait at least n slots before running another task of the same type; it may run other types or stay idle in between.

Return the minimum number of time slots needed to finish every task.

Examples

Input:  tasks = ["X", "X", "X", "Y", "Y", "Z"], n = 2
Output: 7
Explanation: X Y Z X Y idle X.

Input:  tasks = ["P", "Q", "P", "Q", "P"], n = 0
Output: 5

Input:  tasks = ["K","K","K","K","L","M","N","O","P","Q","R"], n = 2
Output: 11
Explanation: K L M K N O K P Q K R: the other tasks fill every gap, so no slot is idle.

Constraints

  • 1 <= len(tasks) <= 10**5, 0 <= n <= 100
  • Target complexity: O(m log m) per round of scheduling (m = number of task types), or O(len(tasks)) with a counting argument; both are accepted.

Goals

  • Model a cooldown constraint with a max-heap of remaining counts
  • Schedule in rounds of n + 1 slots, idling when nothing is runnable
  • Count total elapsed slots including idle ones
Starting Python…