SDE & MLE Prep

621. Task Scheduler

Problem

tasks are letters, each taking one time unit. Two runs of the same letter must be separated by at least n units; in each unit the CPU runs one task or stays idle, and tasks can run in any order. Return the minimum number of units needed for all tasks.

Example: tasks = ["A","A","A","B","B","B"], n = 2 → 8 (A B idle A B idle A B)

Constraints: up to 10⁴ tasks; 0 ≤ n ≤ 100.

The most frequent task(s) dictate the frame: (maxf − 1) full blocks of size n + 1, plus one slot per task tied at maxf. If there are more tasks than slots, no idle is needed → answer is len(tasks).

tasks A A A B B B, n=2      maxf=3, tied=2
A B _ | A B _ | A B         (3-1)*(2+1) + 2 = 8

Complexity: O(n).

class Solution:
    def leastInterval(self, tasks: List[str], n: int) -> int:
        cnt = Counter(tasks).values()
        maxf = max(cnt)
        tied = sum(1 for c in cnt if c == maxf)
        return max(len(tasks), (maxf - 1) * (n + 1) + tied)