Task Scheduler
Medium · Greedy · Array · Hash Table · Greedy · Heap · Counting
Problem
A CPU is given a list of tasks, each labelled by a single character, and a cooldown n. The same label cannot run again until at least n other time units have passed — those units may be other tasks or idle slots.
Each task takes one unit. Tasks may run in any order. Return the fewest time units needed to finish all of them.
Examples
Input: tasks = ['A','A','A','B','B','B'], n = 2 Output: 8
A B idle A B idle A B — the two idle slots are unavoidable because only two labels exist.
Input: tasks = ['A','A','A','B','B','B'], n = 0 Output: 6
No cooldown, so nothing ever waits.
Input: tasks = ['A','A','A','B','B','B'], n = 3 Output: 10
A wider gap means more idling: A B idle idle A B idle idle A B.
Constraints
- 1 <= len(tasks) <= 10^4
- tasks[i] is an uppercase English letter
- 0 <= n <= 100
Approaches
- Simulate with a max-heap and a cooldown queue — time O(len(tasks) · log 26), space O(26)
Related problems
Start free on Cariara · Coding problems · System design studio