InterviewPrepKit

Home / Coding / Heap & Priority Queue

Task Scheduler

medium Original ↗
Solving tips
  • Only the counts of each label matter, not order; the greedy is 'run the most frequent available task first' to spread out the hardest-to-separate letters.
  • The clean answer is the counting formula: max(len(tasks), (maxCount - 1) * (n + 1) + numTied), computable in O(T) time, O(1) space (26 letters).
  • Don't forget the max(len(tasks), ...) clamp: when tasks are plentiful and varied no idling is needed, and the skeleton estimate undershoots the one-slot-per-task lower bound.
  • Pitfall: count ALL labels tied at the maximum frequency for the tail, and if simulating with a heap, re-queue at time + n + 1 (n other intervals between runs), not time + n.

Problem

You are given a list of CPU tasks, each labeled with an uppercase letter AZ, and a non-negative integer n (the cooldown). The CPU works in discrete time intervals: in each interval it either executes exactly one task or sits idle.

The catch: two executions of the same task label must be separated by at least n intervals. In other words, after running task X, the CPU must wait at least n other intervals (running different tasks or idling) before it can run X again. Tasks may be executed in any order.

Return the minimum total number of intervals (work + idle) required to finish every task.

Examples

  • tasks = ["A","A","A","B","B","B"], n = 28 One optimal schedule is A B idle A B idle A B: each pair of same letters is 3 slots apart, satisfying the cooldown of 2.
  • tasks = ["A","C","A","B","D","B"], n = 16 With cooldown 1, alternate letters like A B A B C D — no idle intervals are ever needed.
  • tasks = ["A","A","A","B","B","B"], n = 310 A B idle idle A B idle idle A B: the two most frequent tasks can’t fill the wide gaps, so the CPU idles.

Constraints

  • 1 <= tasks.length <= 10^4
  • tasks[i] is an uppercase English letter (at most 26 distinct labels)
  • 0 <= n <= 100

Think about it first

Hint 1 Only the counts of each letter matter, not the order they appear in the input. Which task should you schedule first when several are available?
Hint 2 Greedily run the task with the most remaining copies among those off cooldown. A max-heap gives you "most remaining" fast, and a FIFO queue of (ready-time, count) tracks who is cooling down.
Hint 3 You can even skip the simulation: the most frequent task (count `f`) forces a skeleton of `f - 1` gaps, each `n + 1` wide. The answer is `max(len(tasks), (f - 1) * (n + 1) + (#tasks tied at f))`.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.