Python coding

Shortest schedule with a cooldown

A processor must run every task in tasks, a string where each letter names a task; each run takes one time unit. Between two runs of the same letter there must be at least gap other units, busy or idle: a letter run at time t can run again at time t + gap + 1 at the earliest. In each unit the processor runs one task or stays idle, and it may take the tasks in any order. Return the fewest units it needs to run them all.

tasks holds uppercase letters and may be empty; gap >= 0 and can be large. Aim for O(n) time, independent of gap.

Besides the tests, one large input (5,000 tasks, a gap of 2,500) with a ~150 ms limit (scaled to your device's speed): brute force won't pass.

  • shortest_schedule("AAABBB", 2) → 8
  • shortest_schedule("AAABBB", 0) → 6
  • shortest_schedule("AAAAAABCDEFG", 2) → 16
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Only the counts matter. The most frequent letter is the bottleneck: its copies must sit gap + 1 slots apart, which fixes a frame of blocks.

Hint 2

With most copies of the top letter there are most - 1 full blocks of gap + 1 slots, then a last block holding each letter tied for the top count. Other letters fill the idle slots.

Hint 3

If the other letters overflow the frame, no slot needs to be idle: the answer is then just len(tasks). Take the larger of the two.

Solution and why it works
pythonO(n) · O(1), at most 26 letters
from collections import Counter


def shortest_schedule(tasks: str, gap: int) -> int:
    counts = Counter(tasks).values()
    most = max(counts, default=0)
    tied = sum(1 for c in counts if c == most)   # letters that share the top count
    # the commonest letter needs most - 1 blocks of gap + 1 slots, then one slot per tied letter
    return max(len(tasks), (most - 1) * (gap + 1) + tied)

Greedy view: place the most frequent letter first, as far apart as allowed. That gives most - 1 blocks of gap + 1 slots plus a tail with every letter tied for the top count, and no schedule is shorter: those copies alone force that span. Every other letter has fewer copies, so it fits one per block in the idle slots; if they overflow, nothing idles and the answer is len(tasks). The trap: simulating tick by tick, which costs O(n × gap) when most ticks are idle.