Priority Queue

Task Scheduler

Medium
Solve it on LeetCode ↗

The problem

Given tasks (letters) and a cooldown n between two identical tasks, return the minimum number of CPU intervals (task or idle) to finish everything.

Stuck? Reveal hints one at a time

How to approach it

  1. 1Count frequencies; find maxFreq and how many tasks reach it (call it ties).
  2. 2Frame the schedule as (maxFreq − 1) full blocks of length n + 1 headed by the most frequent task, plus one final row of the tied tasks.
  3. 3Other tasks fill the idle slots inside blocks; if tasks overflow the frame, the answer is simply tasks.length.
  4. 4Return max(tasks.length, (maxFreq − 1) × (n + 1) + ties).

Key insight

When there are enough distinct tasks to fill every gap, no idling happens and the count is just tasks.length — the max() encodes both regimes in one line.

The solution

Watch out for

  • Forgetting the max() with tasks.length — dense task mixes need zero idles.
  • The heap + cooldown-queue simulation also works and generalizes to streaming variants.