Task Scheduler
Part of Practice: Scheduling & Streams
A CPU must run a list of tasks, each labeled with a capital letter and each taking exactly one time unit. Between two runs of the same label there must be a cooldown gap of at least n time units, during which the CPU can run different tasks or sit idle. Tasks may be executed in any order.
Return the minimum number of time units needed to finish every task, counting idle units. There are up to 10^4 tasks and the cooldown n is between 0 and 100.
Examples
- Input:
- tasks = ["A", "A", "A", "B", "B", "B"], n = 2
- Output:
- 8
One optimal schedule is A → B → idle → A → B → idle → A → B. Each pair of same letters is separated by at least 2 units, and the total is 8 units including 2 idles.
- Input:
- tasks = ["A", "A", "A", "B", "B", "B"], n = 0
- Output:
- 6
With no cooldown, tasks run back to back in any order: 6 units, no idling.
- Input:
- tasks = ["A", "A", "A", "A", "A", "A", "B", "C", "D", "E", "F", "G"], n = 2
- Output:
- 16
The six A's force the frame A ? ? A ? ? A ? ? A ? ? A ? ? A. The other six tasks fill six of the ten gaps; the rest are idle. Total: 16.
Hints
One at a time — struggle first, peek second.
Your thinking space — verify on LeetCode, then mark it.