Task Scheduler

A CPU must run a list of tasks. Each task is a single capital letter, and one task takes exactly one unit of time. In every time unit the CPU either runs one task or sits idle. Tasks may be run in any order.

There is a cooldown rule: two tasks with the same letter must have at least n time units between them (other tasks or idle time). For example with n = 2, an A at time 0 means the next A cannot run before time 3.

Return the least number of time units needed to finish every task.

Constraints

  • 1 <= tasks.length <= 10^4
  • Each task is an uppercase letter from "A" to "Z".
  • 0 <= n <= 100

Examples

Example 1

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

One valid schedule is A B idle A B idle A B: 8 time units. Each A and each B must wait two units before repeating.

Example 2

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

No cooldown, so tasks run back to back: 6 units.

Example 3

Input: tasks = ["A","A","A","A","A","A","B","C","D","E","F","G"], n = 2
Output: 16

A is the bottleneck: A _ _ A _ _ A _ _ A _ _ A _ _ A needs 16 units, and the six other tasks fill 6 of the 10 gap slots, so 4 slots stay idle.

JavaScript you'll use: Heaps and priority queues Map and Set

/**
 * @param {string[]} tasks
 * @param {number} n
 * @return {number}
 */
function leastInterval(tasks, n) {
  
}

Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.