AI-Generated Visualization - This interactive demo was created by Claude AI to help understand LeetCode #621: Task Scheduler. Verify the implementation independently.

Task Scheduler

Given an array of CPU tasks and a cooldown interval n, find the minimum number of intervals needed to execute all tasks. Identical tasks must be separated by at least n intervals.

Greedy LeetCode 621 ↗ Medium

Problem

Task: You are given an array of CPU tasks, each represented by letters A to Z, and a cooldown time n. Each cycle or interval allows the completion of one task. Output the minimum number of intervals required to complete all tasks.

Constraints:

  • 1 ≤ tasks.length ≤ 104
  • tasks[i] is an uppercase English letter
  • 0 ≤ n ≤ 100
  • Identical tasks must be separated by at least n intervals

Example:

tasks = ["A","A","A","B","B","B"], n = 2 → Output: 8
Schedule: A → B → idle → A → B → idle → A → B

Visualization

Formula Calculation
Task Frequencies
Timeline Schedule
Code
fun leastInterval(tasks: CharArray, n: Int): Int {    val freq = IntArray(26)    for (task in tasks) {        freq[task - 'A'] += 1    }    val maxFreq = freq.max()    val maxCount = freq.count { it == maxFreq }    // Formula: (maxFreq - 1) * (n + 1) + maxCount    val result = (maxFreq - 1) * (n + 1) + maxCount    return maxOf(result, tasks.size)}
Status & Log

Explanation

Key Insight

The greedy approach uses a mathematical formula based on the most frequent task. If a task appears max_freq times, we need at least (max_freq - 1) × (n + 1) + max_count intervals, where max_count is the number of tasks with maximum frequency.

The intuition: arrange the most frequent task with cooldown gaps, then fill the gaps with other tasks. If we have enough variety, no idle time is needed and the answer is simply the total number of tasks.

Algorithm

  1. Count the frequency of each task
  2. Find the maximum frequency and count how many tasks have this frequency
  3. Apply formula: (max_freq - 1) × (n + 1) + max_count
  4. The result is the maximum of this formula and the total number of tasks
  5. For visualization, simulate the actual scheduling greedily

Complexity

Time Complexity: O(n) where n is the number of tasks

Space Complexity: O(1) - fixed size array for 26 letters