CodingNodes / Heap / Priority Queue / Task Scheduler System design Space play · ←→ step · R restart

Problem

A CPU must run a list of tasks, each named by a capital letter. One task takes exactly one tick, and tasks can run in any order. The CPU may also sit idle for a tick.

There is a cooling rule: after a task runs, the same task cannot run again until at least n more ticks have passed. Different tasks do not interfere. Return the fewest ticks needed to finish every task.

Constraints

  • 1 ≤ tasks.length ≤ 10 000
  • tasks[i] is a capital letter from "A" to "Z"
  • 0 ≤ n ≤ 100

Examples: pick one to animate

Solutions

TimeO(T) SpaceO(1)

Time: T is the answer, the number of ticks. Every tick does a constant number of heap and queue operations, and the heap never holds more than 26 counts, so each costs a constant.

Space: There are at most 26 different tasks, so the count array, the heap and the queue all stay small.

Every tick, run the task that has the most copies left: it is the hardest to schedule later. A max-heap of counts gives that task. After it runs, it cannot run for n ticks, so it waits in a queue with the tick when it is due back. Because only one task runs per tick, the queue stays in order by due time, so only its front needs checking. If the heap is empty but the queue is not, the tick is idle. The heap is an array the code manages itself, drawn here as array and tree.