Task scheduler with cooldown

Greedily run the most frequent remaining task each tick, using a max-heap of task counts and a queue for tasks that are cooling down.

Time O(n log m)Space O(m)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Greedily run whichever remaining task has the highest count, then let it cool down for n ticks before it can run again. A max-heap ordered by remaining count always surfaces the right task to run; a cooldown queue holds tasks that are temporarily unavailable until they rejoin the heap. If nothing is available on a tick, the CPU idles.

Code

public static int LeastInterval(char[] tasks, int n) {
    var freq = new Dictionary<char, int>();
    foreach (char t in tasks) freq[t] = freq.GetValueOrDefault(t) + 1;
    var heap = new PriorityQueue<char, int>(Comparer<int>.Create((a, b) => b - a));
    foreach (var kv in freq) heap.Enqueue(kv.Key, kv.Value);
    var cooldown = new Queue<(char task, int count, int readyAt)>();
    int time = 0;
    while (heap.Count > 0 || cooldown.Count > 0) {
        time++;
        while (cooldown.Count > 0 && cooldown.Peek().readyAt <= time) {
            var ready = cooldown.Dequeue();
            heap.Enqueue(ready.task, ready.count);
        }
        if (heap.TryDequeue(out char t, out int cnt)) {
            if (--cnt > 0) cooldown.Enqueue((t, cnt, time + n + 1));
        }
    }
    return time;
}
static int leastInterval(char[] tasks, int n) {
    Map<Character, Integer> freq = new HashMap<>();
    for (char t : tasks) freq.merge(t, 1, Integer::sum);
    PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> b[1] - a[1]); // max-heap of {task, count} by count
    for (Map.Entry<Character, Integer> kv : freq.entrySet()) heap.offer(new int[]{kv.getKey(), kv.getValue()});
    Queue<int[]> cooldown = new ArrayDeque<>(); // {task, count, readyAt}
    int time = 0;
    while (!heap.isEmpty() || !cooldown.isEmpty()) {
        time++;
        while (!cooldown.isEmpty() && cooldown.peek()[2] <= time) {
            int[] ready = cooldown.poll();
            heap.offer(new int[]{ready[0], ready[1]});
        }
        int[] top = heap.poll();
        if (top != null) {
            int t = top[0], cnt = top[1];
            if (--cnt > 0) cooldown.offer(new int[]{t, cnt, time + n + 1});
        }
    }
    return time;
}
int leastInterval(const vector<char>& tasks, int n) {
    unordered_map<char, int> freq;
    for (char t : tasks) freq[t]++;
    priority_queue<pair<int, char>> heap; // max-heap by count
    for (auto& [task, count] : freq) heap.push({count, task});
    queue<tuple<char, int, int>> cooldown; // {task, count, readyAt}
    int time = 0;
    while (!heap.empty() || !cooldown.empty()) {
        time++;
        while (!cooldown.empty() && get<2>(cooldown.front()) <= time) {
            auto [task, count, readyAt] = cooldown.front(); cooldown.pop();
            heap.push({count, task});
        }
        if (!heap.empty()) {
            auto [cnt, t] = heap.top(); heap.pop();
            if (--cnt > 0) cooldown.push({t, cnt, time + n + 1});
        }
    }
    return time;
}
import heapq
from collections import Counter, deque

def least_interval(tasks: list[str], n: int) -> int:
    freq = Counter(tasks)
    heap = []  # max-heap by count (counts stored negated)
    for task, count in freq.items(): heapq.heappush(heap, (-count, task))
    cooldown = deque()  # (task, count, ready_at)
    time = 0
    while heap or cooldown:
        time += 1
        while cooldown and cooldown[0][2] <= time:
            task, count, _ = cooldown.popleft()
            heapq.heappush(heap, (-count, task))
        if heap:
            neg, t = heapq.heappop(heap)
            cnt = -neg - 1
            if cnt > 0: cooldown.append((t, cnt, time + n + 1))
    return time

Tips

In the .NET library

This greedy-plus-cooldown shape is the same one behind rate limiting: serve the highest-priority ready request, and anything over its limit waits in a queue until its window reopens.