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 - Optimal Solution INPUT tasks = ["A","A","A","B","B","B"] A A A B B B Cooldown Period n = 2 Task Frequency: A: 3 B: 3 maxFreq = 3 maxCount = 2 (A and B) total tasks = 6 ALGORITHM STEPS 1 Count Frequencies Find task with max count 2 Calculate Frame Size partCount = maxFreq - 1 3 Calculate Empty Slots emptySlots = partCount * n 4 Apply Formula max(tasks.length, result) partCount = 3 - 1 = 2 emptySlots = 2 * 2 = 4 result = (2+1) * 2 + 2 = 8 max(6, 8) = 8 Timeline Pattern: [A][B][_][A][B][_][A][B] _ = idle slot FINAL RESULT CPU Execution Timeline A 1 B 2 - 3 A 4 B 5 - 6 A 7 B 8 Task A (3x) Task B (3x) Idle (2x) Output 8 OK - Verified! 8 CPU intervals needed Cooldown n=2 satisfied Key Insight: The optimal schedule arranges tasks by placing the most frequent task first, then filling gaps with other tasks. Formula: result = (maxFreq - 1) * (n + 1) + maxCount. If all tasks fit without extra idle time, return tasks.length. Time Complexity: O(n) | Space Complexity: O(1) - only 26 letters possible TutorialsPoint - Task Scheduler | Optimal Solution (Greedy Formula)
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