mediumHeapHeap / Priority Queue

Task Scheduler

mediumTime: O(n log 26) = O(n)Space: O(1)

Signals to notice

schedule tasks with cooldownmost frequent task limits throughputidle slots

Brute force first

Simulate each time unit, greedily picking the most frequent available task. Correct but slow simulation. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

The key insight

The total time = max(n, (maxFreq - 1) × (cooldown + 1) + countOfMaxFreq). The most frequent task creates mandatory gaps — other tasks fill those gaps. If there are enough diverse tasks, no idle time is needed. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

What must stay true

The most frequent task determines the minimum timeline. It must wait (cooldown + 1) units between executions, creating (maxFreq - 1) gaps. If other tasks fill all gaps, the answer is just n. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Easy way to go wrong

Trying to simulate task-by-task — the formula approach is and captures all cases. The key insight is that idle time only exists when there aren't enough diverse tasks to fill the gaps. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Heap / Priority Queue Pattern