CodeArchon

mediumHeap / Priority QueueFacebookAmazonGoogle

CPU Cooldown Scheduler

A single-core CPU dispatches tasks of various types; each type must wait N cycles before running again. Minimize total cycles (including idles).

Given a list of CPU tasks (letters) and a non-negative integer n representing cooldown between identical tasks, return the least number of time units the CPU takes to finish all tasks.

Choose approach

A
0
tick
A
1
A
2
B
3
B
4
B
5
MapMax-Heap by remaining count
B→3
1/8
Narrationstep 1 of 8

Tick 1: Run A. Cooldown queue size = 1.

1import heapq, collections
2def leastInterval(tasks, n):
3 heap = [-c for c in collections.Counter(tasks).values()]
4 heapq.heapify(heap)
5 q = collections.deque()
6 time = 0
7 while heap or q:
8 time += 1
9 if heap:
10 c = -heapq.heappop(heap) - 1
11 if c: q.append((-c, time + n))
12 if q and q[0][1] == time:
13 heapq.heappush(heap, q.popleft()[0])
14 return time
Variables
time=1
scheduled=A
heap=B:3
cooldown=A@3

How to think about it

  1. Running the most-frequent task first minimizes idles.
  2. Cooldown queue stores tasks with their earliest re-admit tick.
  3. Idle cycle = heap empty but queue has future-ready tasks.

Edge cases to catch in interview

  • n = 0 -> no cooldown; answer = len(tasks).
  • All tasks same letter -> many idles.

Examples

Example 18
{"tasks":["A","A","A","B","B","B"],"n":2,"values":["A","A","A","B","B","B"]}

A B idle A B idle A B

Example 26
{"tasks":["A","C","A","B","D","B"],"n":1,"values":["A","C","A","B","D","B"]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed