The problem “621. Task Scheduler” on LeetCode can be described as follows:
You are given a char array representing tasks CPU needs to do. It contains uppercase English letters where different letters represent different tasks. Tasks could be done without original 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. That means if you have two same tasks, there must be at least n
units of time between them.
You need to return the least number of units of times that the CPU will take to finish all the given tasks.
Example:
n
be negative?
n
is a non-negative integer.from collections import Counter
def leastInterval(tasks, n):
task_counts = Counter(tasks)
max_freq = max(task_counts.values())
# Find the number of tasks that have the max frequency
max_freq_tasks = sum(1 for task, count in task_counts.items() if count == max_freq)
intervals_needed = (max_freq - 1) * (n + 1) + max_freq_tasks
return max(intervals_needed, len(tasks))
# Example usage:
tasks = ["A", "A", "A", "B", "B", "B"]
n = 2
print(leastInterval(tasks, n)) # Output: 8
Counter
to count the frequency of each task.n + 1
gives the total slots needed for each cycle. max_freq_tasks
accounts for additional slots needed if there are multiple tasks with the maximum frequency.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?