Taro Logo

Task Scheduler

#39 Most AskedMedium
Topics:
ArraysGreedy Algorithms

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 <= 104
  • tasks[i] is an uppercase English letter.
  • 0 <= n <= 100

Solution


Clarifying Questions

When 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:

  1. What is the character set of the tasks (e.g., are they limited to uppercase English letters 'A'-'Z'), and what are the constraints on the size of the task array and the cooling period $n$?
  2. Can the cooling period $n$ be 0, and if so, does that mean tasks can be executed back-to-back without any idle time?
  3. Since the problem asks for the *least number of units of time*, do we need to return the actual schedule/sequence of tasks, or just the total integer count of time units?
  4. Are all tasks guaranteed to be valid characters, and can the input task array be empty?
  5. If multiple valid task schedules yield the same minimum total time, does it matter which order we schedule them in, as long as the total unit count is minimized?

Brute Force Solution

Approach

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:

  1. Start by looking at the remaining tasks that still need to be completed.
  2. Try picking any valid task that is allowed to be done next, keeping in mind the cooling period rule.
  3. If no valid task can be done right away because of the cooling period, you must wait, which adds empty time to your schedule.
  4. Once you pick a task, pretend you actually scheduled it, and then repeat the process to find the next task.
  5. Keep trying every possible combination of task orders until all tasks from your original list are successfully scheduled.
  6. Compare the total time taken by each of these different schedules.
  7. Select the final schedule that takes the absolute least amount of total time to finish everything.

Code Implementation

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)

Big(O) Analysis

Time Complexity
O(n!) – In the worst-case brute force approach, we recursively try every possible permutation of the n tasks to find the optimal schedule. At the first step, we have up to n choices, at the second step n minus 1 choices, and so on down to 1 choice. This creates a decision tree with n factorial possible task orderings. Since we must evaluate all of these combinations to find the one with the minimum time, the number of operations grows proportionally to n * (n-1) * (n-2) * ... * 1, which simplifies to O(n!).
Space Complexity
O(1) – The algorithm tracks task frequencies using a fixed-size array or hash map of size 26 for the English alphabet, independent of the total number of tasks N. The auxiliary memory required for these counters and loop variables remains completely constant regardless of how large the input list grows. Since no dynamic data structures scale with the input size N, the extra memory used stays at a constant upper bound. Therefore, the space complexity simplifies to O(1) auxiliary space.

Optimal Solution

Approach

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:

  1. Identify which task appears the most frequently and determine how many times it needs to be done.
  2. Imagine creating a grid or framework where each row represents the mandatory waiting time between identical tasks, stretched out to match the frequency of our most common task.
  3. Place this most frequent task at the very beginning of each row in our framework.
  4. Take the remaining tasks and fill them into the available slots in our framework, starting from the top row and moving left to right.
  5. If we run out of space in our current rows and have extra tasks left over, simply extend our rows or let tasks spill over naturally because the waiting time will automatically be satisfied.
  6. Count the total number of filled slots in our framework, accounting for any required waiting gaps, to find the absolute minimum time needed to finish all tasks.

Code Implementation

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))

Big(O) Analysis

Time Complexity
O(n) – To find the time complexity, let N be the total number of tasks in the input array. First, we iterate through all N tasks to count their frequencies, and then we process the fixed 26 uppercase English letters to find the maximum frequency and calculate the required slots. Since the number of unique tasks is bounded by a constant 26, counting frequencies and building the mathematical framework takes time proportional to the total number of tasks N. This means the operations scale linearly with the input size, simplifying the total time complexity to O(n).
Space Complexity
O(1) – To determine the most frequent tasks and build the scheduling framework, we utilize a fixed-size frequency array of size 26 to store the counts of each English uppercase letter. Since the alphabet size is constant and does not scale with the total number of tasks N, the auxiliary data structures require a constant amount of extra memory. Variables used for calculating maximum frequencies and empty slots consume only a few scalar memory locations. Therefore, the total extra memory remains constant, resulting in an optimal space complexity of O(1).

Edge Cases

Empty task array where input is null or empty
How to Handle:
Return zero immediately since no tasks require processing time.
Cooling period is zero
How to Handle:
Return the total number of tasks as no idle time is required between identical tasks.
All tasks are unique and cooling period is large
How to Handle:
Return the total number of tasks because unique tasks never conflict with each other regardless of the cooling period.
All tasks are identical
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Utilize standard integer types that safely fit within 32-bit limits or language-appropriate data types for arithmetic operations.
0/245 completed