heap
priority-queue
greedy
You are given a list of CPU tasks represented by uppercase letters. Each task takes exactly one interval, and the same letter must be separated by at least n idle or different-task intervals before it can run again. Return the minimum number of intervals needed to finish all tasks.
Input / output
- Input:
tasks: string[],n: int - Output: integer minimum number of intervals
Examples
tasks = ["A","A","A","B","B","B"],n = 2returns8because one optimal schedule isA, B, idle, A, B, idle, A, B.tasks = ["A","C","A","B","D","B"],n = 1returns6because no idle time is needed.tasks = ["A","A","A","B","B","B"],n = 0returns6.
Constraints
1 <= tasks.length <= 10^4- Each
tasks[i]is a single uppercase English letter 0 <= n <= 100
Target complexity
- Aim for
O(tasks.length)time andO(1)extra space beyond the fixed-size frequency table.
Hints
- The task with the highest frequency creates the tightest spacing requirement. Start by imagining that task placed first.
- Count how many tasks tie for the maximum frequency. They all occupy the last row of the same scheduling frame.
Follow-up How would you build an explicit schedule string if an interviewer asked you to print one valid timeline instead of only the minimum length?
Examples
Example 1
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Example 2
Input: tasks = ["A","C","A","B","D","B"], n = 1
Output: 6
Example 3
Input: tasks = ["A","A","A","B","B","B"], n = 0
Output: 6
🔒 6 hidden
Running will execute all 9 cases, including 6 hidden ones.