You are given an array of CPU tasks, each labeled with a letter from A to Z, and a number n. Each CPU interval can be idle or allow the completion of one task. Tasks can be completed in any order, but there's a constraint: there has to be a gap of at least n intervals between two tasks with the same label.
Return the minimum number of CPU intervals required to complete all tasks.
Example 1:
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A possible sequence is: A -> B -> idle -> A -> B -> idle -> A -> B.
After completing task A, you must wait two intervals before doing A again. The same applies to task B. In the 3rd interval, neither A nor B can be done, so you idle. By the 4th interval, you can do A again as 2 intervals have passed.
Example 2:
Input: tasks = ["A","C","A","B","D","B"], n = 1
Output: 6
Explanation: A possible sequence is: A -> B -> C -> D -> A -> B.
With a cooling interval of 1, you can repeat a task after just one other task.
Example 3:
Input: tasks = ["A","A","A", "B","B","B"], n = 3
Output: 10
Explanation: A possible sequence is: A -> B -> idle -> idle -> A -> B -> idle -> idle -> A -> B.
There are only two types of tasks, A and B, which need to be separated by 3 intervals. This leads to idling twice between repetitions of these tasks.
Constraints:
1 <= tasks.length <= 104tasks[i] is an uppercase English letter.0 <= n <= 100When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a list of different tasks that need to be completed, but identical tasks must have a mandatory cooling period of waiting time between them. The brute force approach tries every single possible order in which you could schedule these tasks.
Here's how the algorithm would work step-by-step:
def least_interval_brute_force(task_list, cooling_period):
# We track the last time each task was executed to strictly enforce the cooling period rule
last_execution_time = {}
def find_shortest_schedule(current_time, remaining_tasks):
if not remaining_tasks:
return current_time
minimum_total_time = float('inf')
unique_remaining = set(remaining_tasks)
for task_identifier in unique_remaining:
last_time = last_execution_time.get(task_identifier, -float('inf'))
# We must determine if enough time has elapsed since the last run to avoid violating rules
if current_time - last_time > cooling_period:
previous_execution_time = last_execution_time.get(task_identifier)
last_execution_time[task_identifier] = current_time
next_tasks_list = list(remaining_tasks)
next_tasks_list.remove(task_identifier)
schedule_duration = find_shortest_schedule(current_time + 1, next_tasks_list)
minimum_total_time = min(minimum_total_time, schedule_duration)
if previous_execution_time is not None:
last_execution_time[task_identifier] = previous_execution_time
else:
del last_execution_time[task_identifier]
# If no tasks are ready immediately, we must advance time to respect the mandatory cooling delay
if minimum_total_time == float('inf'):
idle_schedule_duration = find_shortest_schedule(current_time + 1, remaining_tasks)
minimum_total_time = min(minimum_total_time, idle_schedule_duration)
return minimum_total_time
return find_shortest_schedule(0, task_list)The optimal approach focuses on the most frequent tasks first because they are the hardest to fit within the required cooldown period. By building a schedule around these heavy hitters, we naturally create the necessary waiting spaces for everything else.
Here's how the algorithm would work step-by-step:
from collections import Counter
def least_interval(task_list, cooling_period):
# Counting frequencies lets us prioritize the most constrained tasks immediately.
task_counts = Counter(task_list)
most_frequent_task, max_frequency = task_counts.most_common(1)[0]
empty_slots = (max_frequency - 1) * (cooling_period + 1)
slots_to_fill = max_frequency
for task_name, task_frequency in task_counts.items():
if task_name == most_frequent_task:
continue
slots_to_fill += min(task_frequency, max_frequency - 1)
# Ensuring total time accounts for both forced idle intervals and extra overflow tasks.
return max(len(task_list), empty_slots + sum(1 for task_name, task_frequency in task_counts.items() if task_frequency == max_frequency))| Case | How to Handle |
|---|---|
| Empty task array where input is null or empty | Return zero immediately since no tasks require processing time. |
| Cooling period is zero | Return the total number of tasks as no idle time is required between identical tasks. |
| All tasks are unique and cooling period is large | Return the total number of tasks because unique tasks never conflict with each other regardless of the cooling period. |
| All tasks are identical | Calculate the result using the formula based on the frequency of the single task and the cooling interval plus one. |
| Multiple tasks share the same maximum frequency | Account for all most frequent tasks in the mathematical formula by adding the count of tasks that tie for the maximum frequency. |
| Cooling period is very small and diverse tasks can completely fill the idle slots | Return the exact length of the tasks array since no idle states are triggered during execution. |
| Maximum possible constraints where task array length is extremely large | Use a frequency array or hash map running in linear time to ensure optimal scaling and avoid time limit exceed errors. |
| Integer overflow during time calculation with large inputs | Utilize standard integer types that safely fit within 32-bit limits or language-appropriate data types for arithmetic operations. |