This problem follows the Greedy + Heap pattern, commonly found in the Heap / Priority Queue category. Recognizing this pattern is key to solving it efficiently in an interview setting.
Always pick the most frequent task. Use a heap + cooldown queue.
Always schedule the most frequent task first — this minimizes idle time. The formula (maxFreq-1)*(n+1)+countOfMax gives the answer directly.
count = Counter(tasks)
heap = [-c for c in count.values()]
heapify(heap)
time = 0
while heap:
cycle = []
for _ in range(n + 1):
if heap: cycle.append(heappop(heap))
for c in cycle:
if c + 1 < 0: heappush(heap, c + 1)
time += n + 1 if heap else len(cycle)
return timePractice Task Scheduler and similar Heap / Priority Queue problems with flashcards. Build pattern recognition through active recall.
Practice this problem