0:00 / 0:00

Find the fewest slots to run every task with n idle gaps between repeats. The most frequent task sets a frame; the rest fill its gaps.

▼

The problem

LeetCode 621 (Medium). Given CPU tasks (capital letters) and a cooldown n (two runs of the same task need at least n intervals between them), return the minimum number of intervals the CPU needs to finish every task. In each interval it runs one task or stays idle.

Examples: tasks = ["A","A","A","B","B","B"], n = 2 → 8 (A B idle A B idle A B); the same tasks with n = 0 → 6.

TRY IT ON LEETCODE ▶

The solution

from collections import Counter

def leastInterval(tasks, n):
    counts = Counter(tasks)
    top = max(counts.values())
    ties = sum(c == top for c in counts.values())
    frame = (top - 1) * (n + 1) + ties
    return max(len(tasks), frame)

Transcript

Task Scheduler. A CPU runs one task per interval. Tasks are letters, and two runs of the same letter need at least n intervals between them. The CPU may sit idle. Find the fewest intervals to finish them all.

Take three A's and three B's, with n equal to two. Run A, then B. A is still cooling, so the CPU idles. Then A, B, idle, A, B. Six tasks and two idles: eight intervals.

The direct way simulates the clock. Each interval, pop the ready task with the most copies left from a heap, or idle. It pays for every tick: three A's and a B, with n equal to four, take eleven ticks, seven of them idle.

Better: the busiest task sets the frame. A runs three times, so make three rows of n plus one slots. A starts each row, so its copies are n plus one apart. Other letters fill the rows, one per row, so they stay apart too. B ties A, so it joins the last row. The empty slots idle. Frame: top count minus one, times n plus one, plus the ties.

If the gaps run out, say with two C's and two D's, the C's fill the idles, the D's don't fit, and the rows just get wider. Nothing idles, so the answer is the task count, ten. Take the larger of the two.

In code: count each letter. Find the top count and how many letters tie for it. Build the frame, and return the larger of the frame and the number of tasks.

On the example: the top count is three, with two ties. Three minus one is two, times three is six, plus two is eight. Eight beats six tasks. With n equal to zero, the frame is two plus two, four, so the six tasks win.

Counting is one pass over the tasks, and there are at most twenty six letters. So time is order N, and space is order one.

Count the busiest task, build its frame, and let the rest fill in. That's Task Scheduler.