Given CPU tasks labeled with letters and a cooldown n, identical tasks must be at least n intervals apart. Each interval runs one task or idles. Return the minimum number of intervals to finish every task.
The most frequent task (count f) forces f − 1 frames of length n + 1, plus a final partial frame holding every task tied for the max. If there are enough other tasks to fill all gaps, the answer is just the number of tasks.
1function leastInterval(tasks: string[], n: number): number {2const count = new Map<string, number>();3for (const x of tasks) count.set(x, (count.get(x) ?? 0) + 1);4const f = Math.max(...count.values());5const tied = [...count.values()].filter((c) => c === f).length;6return Math.max(tasks.length, (f - 1) * (n + 1) + tied);7}
Count each task.
Space: play/pause · ←/→: step