Magicsheet logo

Task Scheduler

Medium
49%
Updated 6/1/2025

Task Scheduler

What is this problem about?

The Task Scheduler interview question is a classic CPU management simulation. You are given a list of tasks represented by characters (e.g., 'A', 'B', 'C') and a cooling time n. Each task takes one unit of time to complete. However, if you perform two tasks of the same type, there must be at least n units of time (cooldown) between them. During this cooldown, the CPU can either perform a different task or stay idle. Your goal is to find the minimum total time required to finish all tasks.

Why is this asked in interviews?

This "Medium" difficulty problem is extremely popular at companies like Meta, Amazon, and Google. it evaluates a candidate's ability to apply Greedy logic and Priority Queue data structures to a resource management scenario. It tests whether you can identify the "bottleneck" (the task that appears most frequently) and how it dictates the minimum time. Solving this problem efficiently shows that you can think about scheduling and load balancing under constraints.

Algorithmic pattern used

The primary patterns are Greedy and the Heap (Priority Queue) interview pattern.

  1. Greedy Strategy: Always prioritize the task with the highest remaining frequency.
  2. Heap-based Simulation: Use a Max-Heap to store frequencies of tasks. At each step, try to pick up to n+1 distinct tasks from the heap. If you pick fewer than n+1 tasks and there are still tasks left to do, you must add "idle" time.
  3. Mathematical Formula: Alternatively, the result is max(total_tasks, (max_freq - 1) * (n + 1) + number_of_tasks_with_max_freq). This formula calculates the space created by the most frequent task and fills it with others.

Example explanation

Tasks: [A, A, A, B, B], n = 2.

  1. Max frequency is 3 (for 'A').
  2. Pattern: A _ _ A _ _ A. (Cooldown of 2 between A's).
  3. Fill the gaps with 'B': A B _ A B _ A.
  4. Total time = 7 units. (Tasks + 2 idles). If we had another task 'C', it could fill another gap: A B C A B _ A. Still 7 units.

Common mistakes candidates make

A common error is not accounting for the case where there are so many different tasks that no idle time is needed at all (in which case the answer is simply the length of the task list). Another mistake is failing to handle the "tails"—the tasks that have the same maximum frequency as the bottleneck task, which add extra units at the end of the schedule.

Interview preparation tip

When preparing for the Task Scheduler coding problem, focus on both the simulation approach (using a Max-Heap and a Queue) and the mathematical approach. Interviewers often start with the simulation as it’s more intuitive and then ask for an O(1) space optimization using the formula. Mastering the Greedy interview pattern is crucial here.

Similar Questions