← Whiteboard questions

Task Scheduler

Run jobs with a cooldown in the fewest minutes

DSA, Medium, Heap / Priority Queue

Which structure or algorithm, and what does it cost.

A machine runs one job each minute, or sits idle for a minute. The string jobs lists the jobs to run, one letter per job, and each letter is a job type. After the machine runs a job of some type, it must wait cool more minutes before it may run that type again. It may run other types or stay idle in between. The jobs can run in any order. Return the smallest number of minutes needed to finish every job.

Examples

Input jobs = "AAABBC", cool = 2
Output 7
Why one order is A B C A B idle A. The three A jobs force two gaps of two minutes.
Input jobs = "AAABBB", cool = 2
Output 8
Why A and B tie for the most jobs, so both end the schedule: A B idle A B idle A B.
Input jobs = "XXXXY", cool = 2
Output 10
Why X runs four times with two minutes between runs. Only one other job exists, so most gaps stay idle.

Constraints

Your answer must contain

Target Aim for O(n) time, because there are at most 26 job types.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

The type that appears most often is the hardest to place. Think about what it forces on the schedule.

Hint 2 the approach

Work in rounds of cool plus one minutes. In each round, you want to run as many different types as possible.

Hint 3 the key step

Keep a max-heap of remaining counts. Each round, pop up to cool plus one types and run one job of each. If jobs remain, it lasts cool plus one minutes.

Walkthrough

Full walkthrough brute force to best

Brute force

Try every order of the jobs, with every placement of idle minutes, and keep the shortest valid schedule. The number of orders grows like n factorial, so even 15 jobs is out of reach.

Better method

Count the jobs. Let m be the highest count and t the number of types that reach m. The m runs of the most common type leave m - 1 gaps of cool + 1 minutes, and the t top types end the schedule, so the length is (m - 1) * (cool + 1) + t. When there are more jobs than that, the gaps overflow with no idle time, so the answer is the number of jobs. The result is the larger of the two. It is O(n), but it is harder to see why it is right than with the heap rounds.

Best method

Run the types with the most jobs left first, because the most common type is the one that causes idle time. Work in rounds of cool + 1 minutes. In each round, take up to cool + 1 different types from a max-heap of remaining counts, run one job of each, and push back the types that still have jobs. If jobs remain after the round, the round lasts a full cool + 1 minutes, with idle minutes where fewer types were available. The last round lasts only as long as the jobs it ran. A type is never chosen twice in one round, so the gap rule holds between rounds. The greedy is optimal. Let m be the highest count and t the number of types that reach it. Any valid schedule needs (m - 1)(cool + 1) + t minutes for the top types and at least n minutes overall. The rounds reach the larger of the two, so nothing shorter exists.

Hand trace

Run on jobs "AAABBC" with cool = 2. The counts are A 3, B 2, C 1. Round 1: run A, B and C. A 2 and B 1 are left, so the round lasts 3 minutes. Time 3. Round 2: run A and B. A 1 is left, so the round lasts 3 minutes, with one idle. Time 6. Round 3: run A. Nothing is left, so the round lasts 1 minute. Time 7.

Code

import heapq
from collections import Counter
def least_time(jobs, cool):
    heap = [-c for c in Counter(jobs).values()]     # negated counts: heapq is a min-heap
    heapq.heapify(heap)
    minutes = 0
    while heap:
        used, left = 0, []
        for _ in range(cool + 1):
            if not heap:
                break
            count = heapq.heappop(heap) + 1         # run one job of this type
            used += 1
            if count < 0:
                left.append(count)
        for count in left:
            heapq.heappush(heap, count)
        minutes += cool + 1 if heap else used
    return minutes

Time and memory

O(n) time: each job is pushed and popped about once, and the heap holds at most 26 counts, so each heap step is constant. O(1) extra memory for the counts of 26 types.

Common mistakes

  • Adding idle time after the last job. The last round lasts only as long as its jobs, so "AAABBC" with cool 2 gives 7, not 9.
  • Picking types in alphabet order or from a min-heap. Running the most common type first is what keeps idle time small.
  • Pushing a type back before the round ends. It could then run twice in one round and break the gap rule.
  • In the closed form, adding 1 at the end instead of the number of types tied for the highest count.

Related problems

More Heap / Priority Queue problems
Task Scheduler: hints, walkthrough and Python solution