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.
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.
The primary patterns are Greedy and the Heap (Priority Queue) interview pattern.
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.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.Tasks: [A, A, A, B, B], n = 2.
A _ _ A _ _ A. (Cooldown of 2 between A's).A B _ A B _ A.A B C A B _ A. Still 7 units.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.
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.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Distant Barcodes | Medium | Solve | |
| Least Number of Unique Integers after K Removals | Medium | Solve | |
| Largest Values From Labels | Medium | Solve | |
| Maximize Y‑Sum by Picking a Triplet of Distinct X‑Values | Medium | Solve | |
| Reduce Array Size to The Half | Medium | Solve |