Task Scheduler (LeetCode 621): Solution and Explanation

Medium
Array
Hash Table
Greedy
Sorting
Heap
Counting

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Count each task and push the negated counts into a max-heap.
  2. Start time = 0 and an empty deque q for cooling tasks.
  3. Loop while either the heap or the queue is non-empty, adding 1 to time each iteration.
  4. 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.
  5. If the front of the queue has ready time equal to time, pop it and push its count back onto the heap.
  6. Return time when everything has run.

Step-by-step example

tasks = ["A","A","A","B","B","B"], n = 2
  1. 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.
  2. Time 3: the heap is empty, so the CPU idles. A is ready at 3, so it returns to the heap.
  3. 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.
  4. 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.
  5. 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 time

Time and space complexity

Time

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.

Space

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.