Task CoordinationLoading saved progress…

Task Coordination

You're given a list of tasks to run on a single CPU and a cooldown rule: after a task runs, the same task can't run again until at least cooldown other time units have passed. Each task takes exactly one unit of time. In any unit the CPU may run a different task or simply sit idle. Your job is to return the minimum number of time units — counting idles — needed to finish every task. This is the classic Task Scheduler problem; the inputs are task identifiers (often single characters) and a cooldown count.

Signature

// tasks:    string[]   — task identifiers, e.g. ['A', 'A', 'A', 'B', 'B', 'B'].
//                        Repeats are allowed; that's the whole point.
// cooldown: number     — minimum number of intervals between two runs of the
//                        SAME task. cooldown = 2 means at least two other slots
//                        (other tasks or idles) must sit between two A's.
// returns:  number     — the fewest time units, idles included, to run them all.
function taskCoordination(tasks, cooldown): number;

Examples

// A appears 3×, B appears 3×, cooldown 2.
// One optimal order: A B _ A B _ A B  (two forced idles).
taskCoordination(['A', 'A', 'A', 'B', 'B', 'B'], 2);
// → 8
// Only one task, repeated, with cooldown 2.
// Nothing else can fill the gaps, so the CPU idles: A _ _ A _ _ A.
taskCoordination(['A', 'A', 'A'], 2);
// → 7

Notes

  • Cooldown is a gap, not a wait after the last task. It only constrains the spacing between two runs of the same task. The final task never needs a trailing cooldown — once the last unit runs, you're done.
  • Idles count toward the total. If there aren't enough distinct tasks to fill a forced gap, the CPU sits idle, and each idle unit adds one to the answer.
  • Order is yours to choose. The input is a multiset of tasks; you decide the schedule. Two inputs with the same task counts always produce the same answer.
  • cooldown = 0 means no gap at all. With no cooldown the tasks just run back-to-back, so the answer is exactly tasks.length.
  • Empty input returns 0. No tasks, no time.
  • You don't need to return the schedule itself — only its length. There's a closed-form answer once you know the task frequencies, so you never have to simulate the clock.
Loading editor…