Task Scheduler
MediumThe most frequent task sets the skeleton
Problem
Given task letters and a cooldown n between identical tasks, return the least time (units) to finish all tasks.
The busiest task sets the skeleton of slots; fill gaps with others, adding idles only if needed.
The idea
Arrange the busiest task into slots separated by the cooldown; that skeleton has (maxCount - 1) gaps of n, and the remaining tasks fill those gaps. The answer is therefore max(total tasks, (maxCount - 1) × (n + 1) + tiesAtMax).
The trick
- Only the maximum frequency and how many tasks share it matter.
- Never below the total number of tasks — plenty of variety means no idling.
- A greedy heap simulation gives the same result, more slowly.
This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.
Step 1 of 2. Here's the example — ['A','A','A','B','B','B'], n=2 Values: 2.
1maxFreq f, count of tasks with that freq c2return max(len(tasks), (f-1)*(n+1)+c)Input
- array
- [2]
Output
- answer
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- tasks = ["A","A","A","B","B","B"], n = 2
- Output:
- 8
- Explanation:
- Idle gaps force 8 time units.
Example 2
- Input:
- tasks = ["A","A","A","B","B","B"], n = 0
- Output:
- 6
- Explanation:
- No cooldown → just 6.
Example 3
- Input:
- tasks = ["A","B","C"], n = 2
- Output:
- 3
- Explanation:
- All different → 3.
Practice this problem:LeetCode(opens in a new tab)Search GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.