You are given a list of CPU tasks labeled A–Z and an integer n representing a cooldown period. Between two tasks with the same label, the CPU must wait at least n intervals (idle counts). Return the minimum number of intervals to finish all tasks.
tasks = [A,A,A,B,B,B], n = 28tasks = [A,A,A,B,B,B], n = 06tasks = [A,A,A,A,B,B,B,C,D], n = 210maxFreq (highest frequency)maxCount = number of tasks sharing maxFreqpartCount = maxFreq − 1 partitions; partLen = n + 1 slots eachemptySlots = partCount × partLen − (tasks.length − maxCount)return tasks.length + max(0, emptySlots)The most frequent task (say A with frequency f) forces a minimum structure: f−1 partitions of width n+1 separate its appearances, with the final chunk appended at the end. Other tasks slot into the partitions; any leftover partition capacity becomes idle time. If there are enough tasks to fill everything, idle = 0 and the answer is simply tasks.length. Ties at maxFreq share the final tail.
You could simulate every time unit with a max heap of remaining counts and a cooldown queue. That works, but there is a direct formula.
The most frequent task decides the shape of the schedule. If it appears max times, it creates max −1 gaps, each followed by a block of n plus 1 slots. So the frames need max −1, times n plus 1 slots. Every task that ties for the maximum count adds one more slot at the very end. If there are so many tasks that no idle slot is needed, the answer is simply the number of tasks.
The most frequent task builds the frames. The answer can never be less than the number of tasks.
Run the animation above on your own input, or watch the 2:01 video explanation of Task Scheduler with a dry run and Java code.