#621
Task Scheduler
medium· Heap / Priority Queueruns: 0You are given an array of CPU tasks, each labeled with a letter, and a non-negative integer n that represents the cooldown period between two same tasks. Return the minimum number of intervals required to complete all tasks. Tasks can be done in any order; an interval may be idle.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 603
import heapq
from collections import Counter, deque
class Solution:
def leastInterval(self, tasks: list[str], n: int) -> int:
counts = Counter(tasks)
heap = [-c for c in counts.values()]
heapq.heapify(heap)
time = 0
queue = deque()
while heap or queue:
time += 1
if heap:
count = heapq.heappop(heap) + 1
if count != 0:
queue.append((count, time + n))
if queue and queue[0][1] == time:
heapq.heappush(heap, queue.popleft()[0])
return time
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.