LeetEye LeetEye
Hard Heap / Priority Queue ~5 min

Task Scheduler

heap task-scheduler

Problem

Given a characters array tasks, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle.

However, there is a non-negative integer n that represents the cooldown period between two same tasks (the same letter in the array), that is that there must be at least n units of time between any two same tasks.

Return the least number of units of times that the CPU will take to finish all the given tasks.

Examples

Example 1
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
A -> B -> idle -> A -> B -> idle -> A -> B
Example 2
Input: tasks = ["A","A","A","B","B","B"], n = 0
Output: 6
Key Insight

Greedy: always process the most frequent task available.

Greedy: always pick most frequent available task. Use formula: max(total_tasks, (maxFreq-1)*(n+1) + count_of_max_freq_tasks).

How to Approach This Problem

Pattern Recognition: When you see keywords like task scheduler heap, think Heap / Priority Queue.

Step-by-Step Reasoning

1 At each time unit, we should pick:
Answer: Task with highest remaining count
Processing frequent tasks early gives more flexibility to schedule them with gaps.
2 Greedy picks most frequent because:
Answer: It minimizes idle slots needed
High-frequency tasks need the most gaps. Handle them first to fill gaps optimally.
3 To respect cooldown, we:
Answer: Track when each task becomes available
A task used at time t is available again at time t + n + 1.
4 We idle when:
Answer: There are tasks but none are available due to cooldown
If all remaining tasks are on cooldown, must idle.
5 Max-heap helps because:
Answer: O(log k) access to most frequent task
We repeatedly need the task with max remaining count.
6 A queue can track:
Answer: Tasks currently on cooldown
Queue holds (available_time, count) for tasks on cooldown. Pop when time arrives.

Solution

from collections import Counter

def leastInterval(tasks: List[str], n: int) -> int:
    counts = Counter(tasks)
    max_freq = max(counts.values())
    max_freq_count = sum(1 for c in counts.values() if c == max_freq)
    
    # Formula: (max_freq - 1) cycles of (n + 1) slots + final tasks
    min_time = (max_freq - 1) * (n + 1) + max_freq_count
    
    # At least need time for all tasks
    return max(min_time, len(tasks))

Complexity Analysis

Time O(n)
Space O(1)

Master This Pattern

Build intuition with interactive MCQs. Practice Heap / Priority Queue problems in the LeetEye app.

Download LeetEye Free
Practice in LeetEye