PracticeNeetCode ↗LeetCode ↗
Given an array of CPU tasks (each represented by a letter) and a cooldown n — the number of full intervals that must pass before the same task letter can run again — return the minimum number of intervals needed to finish all tasks. The CPU can sit idle if no eligible task is available.
n + 1 between each of its occurrences.maxFreq, the highest count, and maxCount, how many task letters reach that count.(maxFreq - 1) * (n + 1) + maxCount — the most frequent tasks laid out with mandatory gaps, plus their ties packed into the final frame.len(tasks), since enough other tasks can fill gaps that would otherwise sit idle.Time: O(n) — Space: O(1) (at most 26 task letters)
from collections import Counter
def leastInterval(tasks: list[str], n: int) -> int:
counts = Counter(tasks)
max_freq = max(counts.values())
max_count = sum(1 for c in counts.values() if c == max_freq)
intervals = (max_freq - 1) * (n + 1) + max_count
return max(intervals, len(tasks))How the solution above works, piece by piece.
max_freq: the highest count (3). max_count: how many tasks have that count (A and B → 2).max_freq - 1 full blocks of length n + 1, each starting with the most frequent task, plus a final partial row holding the max_count tasks tied for most frequent.len(tasks), hence the max.Running it on tasks = ["A","A","A","B","B","B"], n = 2:
len(tasks).