Skip to content

Task Scheduler

Find the shortest schedule with a cooling gap between equal tasks, filling rounds from a max-heap of counts.

MediumHeaps and Top K
Solve on LeetCode

The problem

You get a list of tasks, each a capital letter, and a cooling time n. The CPU runs one task per unit of time or stays idle, and tasks can run in any order, but two runs of the same letter need at least n other time units between them. Return the fewest units of time needed to finish all the tasks.

Input tasks = ["A", "A", "A", "B", "C"], n = 2

Output 7

A runs three times and needs two slots after each run before the next: A B C A idle idle A takes 7 units.

Input tasks = ["C", "A", "C", "B", "C", "A", "B"], n = 1

Output 7

There are enough other tasks to fill every gap, for example C A C B C A B, so no idle time is needed.

Key constraint: Up to 10,000 tasks but only 26 different letters, so anything you do per letter is cheap.

How to spot the pattern

  • Equal items must be spread out by a minimum gap.
  • At each step you want the task with the most copies left, which is a max-heap question.

The idea

The letters with the most copies left are the ones that can force idle time, so they should run as early and as often as the cooling rule allows. Work in rounds of n + 1 time slots: in each round, run up to n + 1 different letters, always taking the ones with the most copies left from a max-heap, then put back the letters that still have copies. A full round costs n + 1 units, idle slots included, except the last round, which only costs the tasks it actually ran.

Brute force: Try every order of the tasks and simulate the cooling rule for each one, which takes factorial time.

Step by step

  1. 1Count each letter and push every count onto a max-heap.
  2. 2In each round, pop up to n + 1 counts, run one copy of each letter, and keep the counts that still have copies left.
  3. 3Push those reduced counts back onto the heap.
  4. 4If the heap is not empty, the round took n + 1 units; otherwise it was the last round and took only as many units as the tasks it ran.
  5. 5Add up the rounds and return the total.

See the pattern move

The heaps and top k pattern on a small example. Step through it, or press play.

Code

import heapq
from collections import Counter


class Solution:
    def leastInterval(self, tasks: List[str], n: int) -> int:
        # Max-heap of copies left per letter (negated, because heapq is a min-heap).
        heap = [-count for count in Counter(tasks).values()]
        heapq.heapify(heap)
        time = 0
        while heap:
            leftovers = []
            ran = 0
            # One round: up to n + 1 different letters, most copies first.
            for _ in range(n + 1):
                if not heap:
                    break
                count = -heapq.heappop(heap)
                ran += 1
                if count > 1:
                    leftovers.append(count - 1)
            for count in leftovers:
                heapq.heappush(heap, -count)
            # A full round costs n + 1 slots (idle included); the last one only what ran.
            time += n + 1 if heap else ran
        return time

Complexity

Time

O(T)

Space

O(1)

T is the number of tasks: every pop runs one task, and each pop works on a heap of at most 26 counts, so it costs O(log 26). The heap and the counts need room for only 26 letters.

Watch out for

  • Charging a full n + 1 units for the last round, which adds idle time after the final task.
  • Using only the formula (maxCount - 1) * (n + 1) + numMax without taking the larger of it and the number of tasks, which undercounts when many different tasks fill every gap.
  • Running the most frequent letter whenever it is allowed but ignoring the others, instead of always picking the letters with the most copies left.

Follow-up questions

Is there an O(1) formula once you have the counts?

Yes: let maxCount be the highest count and numMax the number of letters that have it. The answer is the larger of the number of tasks and (maxCount - 1) * (n + 1) + numMax: the most frequent letters set up the frame, and if other tasks overflow the gaps, no idle time is needed at all.

What if the tasks must run in the given order?

Then you can't reorder anything, so simulate: remember when each letter last ran and, before running it again, wait until last + n + 1. That is Task Scheduler II.

In Hinglish

Jis task ki sabse zyada copies bachi hain, use pehle chalao. n + 1 slots ka round banao, max-heap se alag-alag tasks bharo, aur jagah bache toh idle.

Related problems