You are given an array of CPU tasks, each labelled with an uppercase letter, and an integer n that represents the cooldown period. Two identical tasks must be separated by at least n time units, during which the CPU may either run a different task or stay idle.
Every task takes exactly one time unit. Return the minimum number of time units the CPU needs to finish all of the tasks, inserting idle slots wherever they are unavoidable.
Example 1
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
One valid ordering is A B idle A B idle A B. The three A's are each two units apart, and so are the three B's, giving 8 total units.
Example 2
Input: tasks = ["A","C","A","B","D","B"], n = 1
Output: 6
There are enough distinct tasks to keep the CPU busy, so no idle slots are needed and the answer equals the number of tasks.
Constraints
1 <= tasks.length <= 10^4tasks[i] is an uppercase English letter.0 <= n <= 100See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI