430. Task Scheduler
A single CPU must run a batch of tasks, given as a string tasks where each uppercase letter is one task and equal letters are the same kind of task. Every task takes exactly one time unit, and the tasks may be executed in any order.
There is one rule: after running a task of some kind, the CPU must wait at least n time units before running another task of the same kind. During a wait the CPU may run different tasks, or it may sit idle for a unit if nothing is allowed to run.
Return the minimum total number of time units (work + idle) needed to finish every task.
Example 1:
Input: tasks = "AAABBB", n = 2
Output: 8
Explanation: One optimal order is A B idle A B idle A B. Each pair of equal letters is separated by at least 2 units, and two of the 8 units are idle.
Example 2:
Input: tasks = "AABBCC", n = 1
Output: 6
Explanation: A B C A B C works with no idling — there are enough different kinds to fill every gap, so the answer is just the number of tasks.
Constraints:
- 1 ≤ tasks.length ≤ 10⁴
- tasks consists of uppercase English letters A-Z
- 0 ≤ n ≤ 100
Hints:
Only the counts of each letter matter, not their order in the input. Which kind of task decides how long the schedule must be?
Place the most frequent task first: its occurrences pin down a skeleton of evenly spaced slots, and every other task just fills the gaps.
If the most frequent task appears f times, its copies force (f − 1) gaps of width n. Count how much of that skeleton the other tasks can fill — and notice the answer can never be less than the number of tasks.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: tasks = "AAABBB", n = 2
Expected output: 8