Skip to content
AI360Xpert
Back to Heap / Priority Queue
Medium

Task Scheduler

Given a characters array `tasks`, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle. However, there is a non-negative integer `n` that represents the cooldown period between two same tasks (the same letter in the array). Return the least number of units of times that the CPU will take to finish all the given tasks.

Examples

Input:tasks = ["A","A","A","B","B","B"], n = 2
Output:8
A -> B -> idle -> A -> B -> idle -> A -> B
Input:tasks = ["A","A","A","B","B","B"], n = 0
Output:6
On this case any permutation of size 6 would work since n = 0.
Input:tasks = ["A","A","A","A","A","A","B","C","D","E","F","G"], n = 2
Output:16
One possible solution is A -> B -> C -> A -> D -> E -> A -> F -> G -> A -> idle -> idle -> A -> idle -> idle -> A

Constraints

  • 1 <= task.length <= 10^4
  • tasks[i] is upper-case English letter.
  • The integer n is in the range [0, 100].

Approach

First, count the frequencies of each task. To minimize idle time, we should always process the task with the highest remaining frequency first. Add the frequencies to a Max Heap. Use a Queue to keep track of tasks that are currently cooling down, storing pairs of `[remaining_frequency, time_available_again]`. At each time step, if the Max Heap has tasks, pop the max, decrement its frequency, and if it's still > 0, add it to the cooling queue. Check if any task in the cooling queue is ready to be processed again and push it back to the Max Heap.

Complexity Analysis

Time Complexity
O(T)
Space Complexity
O(1)

T is the total number of tasks. The heap and queue sizes are bounded by 26 (the number of English letters), so space is O(1) and heap operations take O(1) time.

Solution.java
class Solution {    public int leastInterval(char[] tasks, int n) {        int[] counts = new int[26];        for (char c : tasks) {            counts[c - 'A']++;        }                PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());        for (int count : counts) {            if (count > 0) maxHeap.offer(count);        }                Queue<int[]> q = new LinkedList<>(); // [count, availableTime]        int time = 0;                while (!maxHeap.isEmpty() || !q.isEmpty()) {            time++;                        if (!maxHeap.isEmpty()) {                int count = maxHeap.poll() - 1;                if (count > 0) {                    q.offer(new int[]{count, time + n});                }            }                        if (!q.isEmpty() && q.peek()[1] == time) {                maxHeap.offer(q.poll()[0]);            }        }                return time;    }}