You are given an array of CPU tasks, each represented by letters A-Z, and a number n. Each CPU interval can execute one task or remain idle. Tasks can be completed in any order, but there's a constraint: there must be at least n intervals between two tasks with the same label.

Return the minimum number of CPU intervals required to complete all tasks.

Input & Output

Example 1 — Equal Frequencies
$ Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
💡 Note: A -> B -> idle -> A -> B -> idle -> A -> B. Need 2 idle intervals between same tasks.
Example 2 — No Cooldown
$ Input: tasks = ["A","A","A","B","B","B"], n = 0
Output: 6
💡 Note: No cooldown required, so execute all 6 tasks consecutively.
Example 3 — Sufficient Different Tasks
$ Input: tasks = ["A","A","A","A","A","A","B","C","D","E","F","G"], n = 2
Output: 12
💡 Note: Enough different tasks to fill gaps: A -> B -> C -> A -> D -> E -> A -> F -> G -> A -> A -> A

Constraints

  • 1 ≤ tasks.length ≤ 104
  • 0 ≤ n ≤ 100
  • tasks[i] is an uppercase English letter

Visualization

Tap to expand
Task Scheduler: CPU Execution with CooldownInput:tasks = ["A","A","A","B","B","B"]n = 2CPU Timeline:ABidleABidleAB12345678Constraint: At least n=2 intervals between same task typesA tasks: positions 1, 4, 7 (gaps of 3 ≥ n+1)B tasks: positions 2, 5, 8 (gaps of 3 ≥ n+1)Output: 8 intervals total
Understanding the Visualization
1
Input
Array of tasks with cooldown period n
2
Process
Schedule tasks with n intervals between same types
3
Output
Minimum total intervals needed
Key Takeaway
🎯 Key Insight: The most frequent task determines the minimum schedule length and creates gaps that other tasks can fill
Asked in
Facebook 45 Amazon 38 Google 32 Microsoft 28
187.0K Views
High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen