Task Scheduler

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

You are given an array of CPU tasks, each represented by a single uppercase letter, and a cooling interval n. Each CPU interval allows the CPU to either complete a task or remain idle. The same task cannot be executed again until at least n intervals have passed since its last execution.

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

Examples

Example 1:

Input: tasks = ["A","A","A","B","B","B"], n = 2

Output: 8

Explanation: A possible sequence is: A -> B -> idle -> A -> B -> idle -> A -> B. After completing task A, you must wait 2 intervals before executing A again. The same applies to task B. In the 3rd interval, neither A nor B can be done, so the CPU idles. By the 4th interval, A can be executed again.

Example 2:

Input: tasks = ["A","C","A","B","D","B"], n = 1

Output: 6

Explanation: A possible sequence is: A -> B -> A -> C -> B -> D. With a cooling interval of 1, there are enough distinct tasks to fill every slot without idling.

Example 3:

Input: tasks = ["A","A","A","B","B","B"], n = 0

Output: 6

Explanation: With no cooling interval, the tasks can be executed back-to-back in any order. No idle time is needed.

Constraints

  • 1 <= tasks.length <= 10^4
  • tasks[i] is an uppercase English letter
  • 0 <= n <= 100
Source: Intervals pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle