A processor has a list of tasks to run, each marked with a capital letter. Every time slot it either runs one task or sits idle, and the tasks can go in any order.
There is one rule: after a task with some letter runs, at least n slots must pass before a task with the same letter can run again. Return the smallest number of slots, idle ones included, needed to finish every task.
Example 1
Input: tasks = ["X","X","X","Y","Y","Z"], n = 2 Output: 7 Why: X Y Z X Y idle X keeps two slots between the Xs
2 more examples and the constraints
Example 2
Input: tasks = ["P","Q","P","Q"], n = 0 Output: 4 Why: with no cooldown, nothing ever waits
Example 3
Input: tasks = ["K","K","K","L","M","N","O","P"], n = 2 Output: 8 Why: K L M K N O K P fills every slot, so no idle
Constraints
- 1 ≤ length of tasks ≤ 10,000
- Each task is a letter from A to Z
- 0 ≤ n ≤ 100
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Simulate with a max-heapO(T log k)
- Count the framesO(T)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 tasks | Verdict |
|---|---|---|---|
| Simulate with a max-heap | O(T log k) | Passes; shows the real order | |
| Count the frames | O(T) | Best; one count and a formula |
T = number of tasks, k = number of different letters (at most 26).
Edge cases to test
- No cooldown. With n = 0 the answer is always the number of tasks.
- One kind of task. ["A","A","A","A"] with n = 3 needs 3 idle slots after each A but the last: 13.
- Ties for the top count. ["A","A","B","B","C","C"] with n = 2 ends with a frame of three tasks: 6.
- More tasks than gaps. Example 3 needs no idle slot, so the answer is the task count.
Common mistakes
- Forgetting the max with the number of tasks, which undercounts when no idle is needed.
- Adding 1 for the last frame instead of the number of tied top tasks.
- Using n slots per frame instead of n + 1: the task itself takes a slot too.
How to talk through it
- 1Clarify. Is n the gap between equal tasks, not the frame size? Can n be 0? Do I return the order or just the length?
- 2Simulate first. Greedy with a max-heap: always run the ready task with the most runs left.
- 3Find the shape. The busiest task forces top − 1 frames of n + 1 slots plus a last frame.
- 4Code the formula. Count, find top and ties, and take the max with the task count.
- 5Test out loud. Run n = 0, a single letter, and a case with no idle before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?