Task Scheduler

35 min · leastInterval()

A processor can finish one task per tick, but repeating the same task type too soon overheats its worker. Other tasks can fill the wait; when none fit, the processor idles.

You're given tasks, where each single uppercase letter names a task type. You're also given a cooldown n, the minimum number of intervening time slots required between two copies of the same task.

Choose any execution order and return the fewest total time units needed to finish every task. Both task executions and idle slots count toward the total.

A few ground rules:

  • Every task takes exactly one time unit.
  • You may reorder the input freely.
  • When n = 0, identical tasks may run back to back.

Constraints

  • 1 <= tasks.length <= 100_000
  • Every tasks[i] is one uppercase letter from A through Z.
  • 0 <= n <= 100

Hints

Schedule the busiest type first

If one task appears far more often than the others, it creates the idle pressure. A max-heap can repeatedly choose the available type with the most copies left.

Draw the gaps

Suppose the highest frequency is maxFreq. Place those copies first. The first maxFreq - 1 copies each start a block that needs n following slots before the next copy may appear.

Handle a tie at the top

If numMax task types share the maximum frequency, the last block contains all numMax of them. Compare (maxFreq - 1) * (n + 1) + numMax with tasks.length.

Follow-up

The formula gives only the minimum length. How would you construct one valid schedule with that length, including its idle slots?

Visible cases

Examples

Example 1

ready
Input
tasks = [
  "A",
  "A",
  "A",
  "B",
  "B",
  "B"
]
n = 2
Expected
8
Why
A B idle A B idle A B finishes in 8 time units

Example 2

ready
Input
tasks = [
  "A",
  "A",
  "A",
  "B",
  "B",
  "B"
]
n = 0
Expected
6
Why
with no cooldown, all six tasks can run back to back

Example 3

ready
Input
tasks = [
  "A",
  "A",
  "A",
  "B",
  "B",
  "B",
  "C",
  "C"
]
n = 2
Expected
8
Why
the C tasks fill both gaps, so no idle slot is needed

Interview signal

Asked at

AmazonMetaGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite