InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Heap & Priority Queue

Task Scheduler

medium Original ↗ 00:00

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.

Two executions of the same task label must be separated by at least n intervals: 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))`.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug