BackendML

Task Scheduler

Medium2 min read
The Task Scheduler problem requires scheduling tasks with a cooldown period between two executions of the same task while minimizing the total number of CPU intervals.

Problem

Given an array of characters tasks, where each character represents a task, and an integer n representing the cooldown period, schedule all tasks so that the same task must have at least n intervals between two executions.

During idle intervals, the CPU can remain idle. Return the minimum number of intervals required to complete all tasks.

Example(s)

Consider the following examples to understand the expected input and output.

Example 1

Input
tasks = ["A","A","A","B","B","B"]
n = 2
Output
8

Example 2

Input
tasks = ["A","A","A","B","B","B"]
n = 0
Output
6

Solution

This solution uses a Max Heap to always select the task with the highest remaining frequency. A HashMap or frequency array is used to count how many times each task needs to be executed.

After executing a task, if it still has remaining occurrences, we temporarily place it into a cooldown queue along with the time when it becomes available again. At each interval, tasks whose cooldown has expired are added back to the max heap.

The max heap ensures that the most frequent available task is selected first, while the cooldown queue prevents the same task from being executed before the required cooldown period has passed.
class Solution {
    public int leastInterval(char[] tasks, int n) {
        int[] frequency = new int[26];

        for (char task : tasks) {
            frequency[task - 'A']++;
        }

        PriorityQueue<Integer> maxHeap =
                new PriorityQueue<>(Collections.reverseOrder());

        for (int count : frequency) {
            if (count > 0) {
                maxHeap.offer(count);
            }
        }

        Queue<int[]> cooldown = new LinkedList<>();
        int time = 0;

        while (!maxHeap.isEmpty() || !cooldown.isEmpty()) {
            time++;

            if (!maxHeap.isEmpty()) {
                int remaining = maxHeap.poll() - 1;

                if (remaining > 0) {
                    cooldown.offer(new int[]{remaining, time + n});
                }
            }

            if (!cooldown.isEmpty() &&
                cooldown.peek()[1] == time) {
                maxHeap.offer(cooldown.poll()[0]);
            }
        }

        return time;
    }
}

Complexity

Let T be the total number of tasks and C be the number of distinct task types. Each task can be inserted into and removed from the heap, giving a time complexity of O(T log C).

The frequency array uses O(1) space because there are only 26 uppercase English letters. The max heap and cooldown queue can contain up to O(C) task types, so the extra space complexity is O(C).

Comments

No comments yet. Ask a question or share what helped.