Task Scheduler (LeetCode 621): Solution and Explanation
You have a list of tasks, each labeled with a letter and taking one time unit, and a cooldown n. Two runs of the same letter must be at least n units apart, and the CPU can sit idle. Return the minimum total time needed to finish every task.
Watch it run step by step
Try your own input and write the code →Intuition
Only the counts matter, since tasks with the same letter are interchangeable. Brute force over every ordering is out of the question, so think about which task to run at each moment. The task with the most remaining copies is the one most likely to force idle time at the end, so it should run as soon as it is allowed. That greedy rule, always run the most frequent available task, produces an optimal schedule.
Two things need tracking. Available tasks should be ordered by remaining count, which a max-heap handles. Tasks that just ran are cooling down and are not available until a specific time. Because every task cools down for the same n units, they become ready in the same order they entered the cooldown, so a plain FIFO queue of [remaining count, ready time] pairs is enough.
The simulation advances one time unit per loop iteration. In each unit, run the top task from the heap if there is one, otherwise the CPU idles. If the task still has copies left, put it in the queue with ready time time + n. Then, if the task at the front of the queue becomes ready at this time, move it back onto the heap. When both the heap and the queue are empty, the current time is the answer.
Approach: Max-heap plus cooldown queue simulation
- Count each task and push the negated counts into a max-heap.
- Start
time = 0and an empty dequeqfor cooling tasks. - Loop while either the heap or the queue is non-empty, adding 1 to
timeeach iteration. - If the heap has a task, pop it and add 1 to its negative count. If copies remain, append
[cnt, time + n]to the queue. - If the front of the queue has ready time equal to
time, pop it and push its count back onto the heap. - Return
timewhen everything has run.
Step-by-step example
tasks = ["A","A","A","B","B","B"], n = 2
- The heap holds [-3, -3]. At time 1, run A, which leaves -2 and enters the queue ready at 3. At time 2, run B, which enters the queue ready at 4.
- Time 3: the heap is empty, so the CPU idles. A is ready at 3, so it returns to the heap.
- Time 4: run A, leaving -1, queued for time 6. B is ready at 4, so it returns to the heap. Time 5: run B, queued for time 7.
- Time 6: idle, and A becomes ready. Time 7: run A, its last copy, and B becomes ready. Time 8: run B, its last copy.
- Both structures are empty, so the answer is 8, matching the schedule A B idle A B idle A B.
Code: Python, Java, C++
1class Solution:
2 def leastInterval(self, tasks: List[str], n: int) -> int:
3 count = Counter(tasks)
4 maxHeap = [-cnt for cnt in count.values()]
5 heapq.heapify(maxHeap)
6
7 time = 0
8 q = collections.deque() # pairs of [-cnt, idleTime]
9
10 while maxHeap or q:
11 time += 1
12
13 if maxHeap:
14 cnt = 1 + heapq.heappop(maxHeap)
15 if cnt:
16 q.append([cnt, time + n])
17
18 if q and q[0][1] == time:
19 heapq.heappush(maxHeap, q.popleft()[0])
20 return time1class Solution {
2 public int leastInterval(char[] tasks, int n) {
3 int[] counter = new int[26];
4 for (char task : tasks) counter[task - 'A']++;
5
6 PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
7 for (int count : counter) {
8 if (count > 0) maxHeap.add(count);
9 }
10
11 int time = 0;
12 Queue<int[]> q = new LinkedList<>(); // {cnt, idleTime}
13
14 while (!maxHeap.isEmpty() || !q.isEmpty()) {
15 time++;
16
17 if (!maxHeap.isEmpty()) {
18 int val = maxHeap.poll();
19 val--;
20 if (val > 0) q.add(new int[]{val, time + n});
21 }
22
23 if (!q.isEmpty() && q.peek()[1] == time) {
24 maxHeap.add(q.poll()[0]);
25 }
26 }
27 return time;
28 }
29}1class Solution {
2public:
3 int leastInterval(vector<char>& tasks, int n) {
4 unordered_map<char, int> count;
5 for (char t : tasks) count[t]++;
6
7 priority_queue<int> maxHeap;
8 for (auto& pair : count) maxHeap.push(pair.second);
9
10 int time = 0;
11 queue<pair<int, int>> q; // {cnt, idleTime}
12
13 while (!maxHeap.empty() || !q.empty()) {
14 time++;
15
16 if (!maxHeap.empty()) {
17 int cnt = maxHeap.top() - 1;
18 maxHeap.pop();
19 if (cnt > 0) q.push({cnt, time + n});
20 }
21
22 if (!q.empty() && q.front().second == time) {
23 maxHeap.push(q.front().first);
24 q.pop();
25 }
26 }
27 return time;
28 }
29};Time and space complexity
O(T)
The loop runs once per time unit, where T is the answer, which is at most the number of tasks times n + 1. Each iteration does heap operations on at most 26 entries, which is constant work.
O(1)
The heap, queue and counter each hold at most 26 entries, one per letter, regardless of how many tasks there are.
Other approaches
Counting formula (time O(t), space O(1))
Let maxCount be the highest frequency and numMax the number of letters with that frequency. The answer is max(len(tasks), (maxCount - 1) × (n + 1) + numMax). The most frequent task defines frames of length n + 1, and if other tasks overflow those frames there is no idle time at all.
Common mistakes
- Putting a task that still has copies back onto the heap immediately, which ignores the cooldown and undercounts idle time.
- Checking the queue before the heap in each time unit, which can release a task and run it in the same unit it became ready, shifting the schedule by one.
- Forgetting the
len(tasks)lower bound in the formula version. When there are many distinct tasks, no idling is needed and the frame count underestimates the answer. - Getting the sign wrong on the negated counts. Adding 1 to a negative count uses one copy, and reaching 0 means the task is finished.
Frequently asked questions
Why does the greedy choice of the most frequent task work?
The task with the most remaining copies needs the most cooldown gaps. Running it as early as possible lets other tasks fill those gaps, which minimizes the idle time left at the end.
What is the formula for task scheduler?
max(len(tasks), (maxCount - 1) × (n + 1) + numMax), where maxCount is the highest frequency and numMax is how many letters share it. It computes the answer in linear time without simulating.
Why is a plain queue enough for the cooldown?
Every task cools down for exactly n units, so tasks become ready in the same order they entered the cooldown. A first-in, first-out queue therefore always has the next ready task at its front.