Algo-Sim › Greedy

Task Scheduler

Medium · Greedy · step through it in Java, Python and C++ on your own input

Equal tasks must be n time units apart. Always run the task with the most copies left, idling only when everything is cooling down.

Problem

A CPU runs one task per time unit, or idles. Each letter in tasks is one task, and two runs of the same letter must be at least n units apart. Return the fewest time units needed to finish all tasks, in any order.

Constraints

Edge cases to test

Follow-up questions

Is there a formula?
max(tasks, (maxCount − 1)·(n + 1) + countOfMax): frames built from the most frequent task. O(n) to count.
What if the order must be kept?
Then it is a simulation: remember when each task may next run and wait if needed (LC 2365): O(n) with a map.

Solution

Java

public int leastInterval(char[] tasks, int n) {
    int[] count = new int[26];
    for (char t : tasks) count[t - 'A']++;
    PriorityQueue<Integer> heap = new PriorityQueue<>(Collections.reverseOrder());
    for (int c : count) if (c > 0) heap.offer(c);
    Deque<int[]> cooling = new ArrayDeque<>();  // {tasks left, time it is free again}
    int time = 0, idle = 0;
    while (!heap.isEmpty() || !cooling.isEmpty()) {
        time++;
        if (!heap.isEmpty()) {
            int left = heap.poll() - 1;
            if (left > 0) cooling.offer(new int[] {left, time + n});
        } else {
            idle++;
        }
        if (!cooling.isEmpty() && cooling.peek()[1] == time) {
            heap.offer(cooling.poll()[0]);
        }
    }
    return time;
}

Python

import heapq
from collections import Counter, deque


def least_interval(tasks, n):
    count = Counter(tasks)
    heap = [-c for c in count.values()]
    heapq.heapify(heap)
    cooling = deque()  # (tasks left, time it is free again)
    time = idle = 0
    while heap or cooling:
        time += 1
        if heap:
            left = -heapq.heappop(heap) - 1
            if left > 0:
                cooling.append((left, time + n))
        else:
            idle += 1
        if cooling and cooling[0][1] == time:
            heapq.heappush(heap, -cooling.popleft()[0])
    return time

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int leastInterval(vector<char> &tasks, int n) {
        vector<int> count = vector<int>(26);
        for (char t : tasks)
            count[t - 'A']++;
        priority_queue<int> heap;
        for (int c : count)
            if (c > 0)
                heap.push(c);
        deque<vector<int>> cooling = {}; // {tasks left, time it is free again}
        int time = 0, idle = 0;
        while (!heap.empty() || !cooling.empty()) {
            time++;
            if (!heap.empty()) {
                int left = heap.top() - 1;
                heap.pop();
                if (left > 0)
                    cooling.push_back(vector<int>{left, time + n});
            } else {
                idle++;
            }
            if (!cooling.empty() && cooling.front()[1] == time) {
                heap.push(cooling.front()[0]);
                cooling.pop_front();
            }
        }
        return time;
    }
};

More Greedy problems