Task Scheduler

Medium~25 min

You are given an array of CPU tasks, each represented by a character from A to Z, and a cooling interval n. Each cycle or interval allows the completion of one task. Tasks can be completed in any order, but there is a constraint: identical tasks must be separated by at least n intervals.

Return the minimum number of intervals the CPU will take to finish all the given tasks.

Examples

Example 1
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: One possible schedule: A → B → idle → A → B → idle → A → B. There are 8 total intervals. The key is that each A must be separated by at least 2 intervals from the next A.
Example 2
Input: tasks = ["A","C","A","B","D","B"], n = 1
Output: 6
Explanation: One possible schedule: A → B → C → A → D → B. No idle intervals needed because we can fill every slot with a different task. Total = 6.
Example 3
Input: tasks = ["A","A","A","B","B","B"], n = 0
Output: 6
Explanation: With n = 0, no cooldown is needed. We can execute all 6 tasks in 6 intervals: A → A → A → B → B → B.

Constraints

  • 1 <= tasks.length <= 10^4
  • tasks[i] is an uppercase English letter
  • 0 <= n <= 100
  • Expected time complexity: O(n)
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run