Problem

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), that is that there must be at least n units of time between any two same tasks.

Return the least number of units of times that the CPU will take to finish all the given tasks.

Examples

Example 1:

1
2
3
4
5
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: 
A -> B -> idle -> A -> B -> idle -> A -> B
There is at least 2 units of time between any two same tasks.

Example 2:

1
2
3
4
5
6
7
8
Input: tasks = ["A","A","A","B","B","B"], n = 0
Output: 6
Explanation: On this case any permutation of size 6 would work since n = 0.
["A","A","A","B","B","B"]
["A","B","A","B","A","B"]
["B","B","B","A","A","A"]
...
And so on.

Example 3:

1
2
3
4
5
Input: tasks = ["A","A","A","A","A","A","B","C","D","E","F","G"], n = 2
Output: 16
Explanation: 
One possible solution is
A -> B -> C -> A -> D -> E -> A -> F -> G -> A -> idle -> idle -> A -> idle -> idle -> A

Solution

Method 1 - Using Priority Queue and Hashmap

The approach involves prioritising the task with the highest frequency since the processor must cool down for n seconds between identical tasks. Tasks are added to a priority queue, sorted by frequency. In each round of n, the task with the highest frequency is executed, its frequency is decreased, and it is re-added to the queue after the round.

Here is the approach:

  1. Frequency Count: Count the frequency of each task using a frequency array or dictionary. The most frequent task will determine the organisation around the CPU idle slots.
  2. Organising Tasks:
    • Determine the maximum frequency (maxFreq) of any task.
    • Calculate the number of idle slots required using this maximum frequency. For maxFreq occurrences of a task, the number of idle slots is (maxFreq - 1) * n.
  3. Filling Idle Slots:
    • The remaining tasks should be used to fill these idle slots.
    • If the idle slots are all filled or exceeded by other tasks, then the total time is the number of tasks. Otherwise, it’s determined by the idle slots and task frequencies.
  4. Edge Cases: If n == 0, the CPU can run tasks consecutively, and the result is just the length of the tasks array.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Solution {
    public int leastInterval(char[] tasks, int n) {
        // Step 1: Frequency count of tasks
        int[] freq = new int[26];
        for (char t : tasks) {
            freq[t - 'A']++;
        }
        
        // Step 2: Sort frequencies in descending order
        Arrays.sort(freq);
        int maxFreq = freq[25]; // Maximum frequency of the most frequent task
        
        // Step 3: Compute idle time
        int idleSlots = (maxFreq - 1) * n;
        
        // Reduce idle slots with remaining tasks
        for (int i = 24; i >= 0; i--) {
            idleSlots -= Math.min(freq[i], maxFreq - 1);
        }
        
        // Step 4: Add idle slots (if any) to the total tasks
        return idleSlots > 0 ? tasks.length + idleSlots : tasks.length;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
    def leastInterval(self, tasks: list[str], n: int) -> int:
        # Step 1: Frequency count of tasks
        freq: Counter = Counter(tasks)
        freq_values = sorted(freq.values(), reverse=True)
        max_freq: int = freq_values[0]
        
        # Step 2: Compute idle time
        idle_slots: int = (max_freq - 1) * n
        
        # Reduce idle slots with remaining tasks
        for f in freq_values[1:]:
            idle_slots -= min(f, max_freq - 1)
        
        # Step 3: Add idle slots (if any) to the total tasks
        return len(tasks) + max(0, idle_slots)

Complexity

  • ⏰ Time complexity: O(k), where k is the size of the input tasks list/array. Sorting or heap operations (at most 26 tasks as we calculate frequencies of characters from ‘A’ to ‘Z’): O(1).
  • 🧺 Space complexity: O(1)