sagelearnai

Task Scheduler

Difficulty: Medium · Pattern: Heap & Priority Queue · LeetCode #621

A CPU runs tasks labeled A–Z, one per time unit, or sits idle. Two runs of the same task must be separated by at least n units. Tasks may run in any order. Return the minimum total number of time units needed to finish all tasks.

Examples

text
tasks = ["A","A","A","B","B","B"], n = 2   →  8    (A B idle A B idle A B)
tasks = ["A","C","A","B","D","B"], n = 1   →  6
tasks = ["A","A","A","B","B","B"], n = 3   →  10

Hints

  1. The most frequent task forms the backbone: maxCount − 1 gaps, each of length n.
  2. Other tasks fill the gaps; tasks tied for the max frequency extend the last chunk.
  3. If there are enough distinct tasks to fill every gap, no idling is needed and the answer is just len(tasks).

Approach

Let maxc be the highest frequency and tie the number of tasks with that frequency. Lay out maxc − 1 frames of length n + 1 (the max task plus n slots), followed by a final frame containing the tie tied tasks:

answer = max(len(tasks), (maxc − 1) × (n + 1) + tie)

The max handles the case where there are so many distinct tasks that the frames overflow and no idle time is needed. Simulating with a max-heap and a cooldown queue also works and generalizes better, but is O(T log 26).

Complexity

Time: O(T), for T tasks. Space: O(26).

Python solution
from collections import Counter

def leastInterval(tasks, n):
    counts = Counter(tasks).values()
    maxc = max(counts)
    tie = sum(1 for c in counts if c == maxc)
    return max(len(tasks), (maxc - 1) * (n + 1) + tie)
JavaScript solution
function leastInterval(tasks, n) {
  const cnt = new Map();
  for (const t of tasks) cnt.set(t, (cnt.get(t) || 0) + 1);
  const vals = [...cnt.values()];
  const maxc = Math.max(...vals);
  const tie = vals.filter((c) => c === maxc).length;
  return Math.max(tasks.length, (maxc - 1) * (n + 1) + tie);
}