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:
|
|
Example 2:
|
|
Example 3:
|
|
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:
- 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.
- 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
.
- Determine the maximum frequency (
- 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.
- Edge Cases: If
n == 0
, the CPU can run tasks consecutively, and the result is just the length of thetasks
array.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(k)
, wherek
is the size of the inputtasks
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)