621. Task Scheduler
Medium
Problem:
There are tasks represented from A to Z. At each interval, the CPU can execute only one task, and the same task cannot be executed within 'n' intervals. If no further tasks can be executed, the CPU enters an idle state. Output the minimum number of intervals required to execute all tasks.
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
https://leetcode.com/problems/task-scheduler/
What to learn:
collections.Counter()
A notable feature of the Counter is that it also handles zeros and negative numbers. Thus, adding an empty collection.Counter()
will completely remove items with counts of zero or less from the list.
most_common()
The most_common()
function outputs the items with the highest count first, essentially serving the same role as a maximum heap. However, the items are not extracted using pop()
.
Solution:
A priority queue should be used to extract the items with the highest count one by one, but the challenge is not to extract everything at once. Instead, we need a structure that allows us to update the count after only one extraction.
class Solution:
def leastInterval(self, tasks: List[str], n: int) -> int:
counter = collections.Counter(tasks)
result = 0
while True:
sub_count = 0
for task, _ in counter.most_common(n + 1):
sub_count += 1
result += 1
counter.subtract(task)
# Remove zero and negative counts
counter += collections.Counter()
if not counter:
break
# Cooldown period
result += n - sub_count + 1
return result
Last updated