Task Scheduler

Find the minimum intervals to execute all tasks with cooldown n.

Pattern

Greedy + Heap

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.

Approach

How to Solve It

Always pick the most frequent task. Use a heap + cooldown queue.

Key Insight

Always schedule the most frequent task first — this minimizes idle time. The formula (maxFreq-1)*(n+1)+countOfMax gives the answer directly.

Step-by-step

  1. 1Count task frequencies and put them in a max-heap
  2. 2Process tasks in rounds of (n+1) slots
  3. 3In each round, pick up to (n+1) most frequent tasks
  4. 4If tasks remain but fewer than (n+1) were picked, add idle slots

Pseudocode

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 time
Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(1)
More Heap / Priority Queue Problems

Master this pattern with YeetCode

Practice Task Scheduler and similar Heap / Priority Queue problems with flashcards. Build pattern recognition through active recall.

Practice this problem