Practice · Greedy · 4 of 4

Schedule Tasks with a Cooldown

A processor must run every task in tasks, where each task is named by one uppercase letter. Each task takes one time slot, and in every slot the processor either runs one task or sits idle.

Tasks may run in any order, but between two runs of the same task there must be at least n other slots (running other tasks or idle). Return the smallest number of slots that runs every task.

Example 1

Input
tasks = ["X", "X", "X", "Y", "Y"], n = 2
Output
7
X Y idle X Y idle X: after each X come two other slots before the next one.

Example 2

Input
tasks = ["P", "Q", "R", "P", "Q", "S"], n = 1
Output
6
P Q P Q R S needs no idle slots, because there are enough different tasks to fill the gaps.

Constraints

  • tasks holds 1 to 10⁴ tasks, each an uppercase letter from A to Z.
  • 0 ≤ n ≤ 100
Brush up firstHeap visualiser