← DSA
MEDIUM

Task Scheduler

PracticeNeetCode ↗LeetCode ↗

Given an array of CPU tasks (each represented by a letter) and a cooldown n — the number of full intervals that must pass before the same task letter can run again — return the minimum number of intervals needed to finish all tasks. The CPU can sit idle if no eligible task is available.

Example

Input tasks = ["A","A","A","B","B","B"], n = 2
Output 8

Key Pointers

Step-by-Step Analysis

  1. Count how often each task letter appears.
  2. Find maxFreq, the highest count, and maxCount, how many task letters reach that count.
  3. Compute the frame-based lower bound: (maxFreq - 1) * (n + 1) + maxCount — the most frequent tasks laid out with mandatory gaps, plus their ties packed into the final frame.
  4. Return the larger of that bound and len(tasks), since enough other tasks can fill gaps that would otherwise sit idle.

Complexity

Time: O(n) — Space: O(1) (at most 26 task letters)

Code

from collections import Counter

def leastInterval(tasks: list[str], n: int) -> int:
    counts = Counter(tasks)
    max_freq = max(counts.values())
    max_count = sum(1 for c in counts.values() if c == max_freq)

    intervals = (max_freq - 1) * (n + 1) + max_count
    return max(intervals, len(tasks))

Code Explanation

How the solution above works, piece by piece.

  1. Only the most frequent tasks can force idle time, so count frequencies.
  2. max_freq: the highest count (3). max_count: how many tasks have that count (A and B → 2).
  3. Picture max_freq - 1 full blocks of length n + 1, each starting with the most frequent task, plus a final partial row holding the max_count tasks tied for most frequent.
  4. Other tasks fill idle slots. If there are more tasks than slots, no idle is needed and the answer is len(tasks), hence the max.
  5. O(n) time to count, O(1) space (at most 26 task types).

Visual Walkthrough

Running it on tasks = ["A","A","A","B","B","B"], n = 2:

Schedule A B idle A B idle A BA1B2idle3A4B5idle6A7B8block of n + 1 = 3block of n + 1 = 3last row: 2 tasks(max_freq − 1) × (n + 1) + max_count = (3 − 1) × 3 + 2 = 8
The most frequent tasks (A and B, 3 each) decide the length: they need n = 2 gaps between repeats, which gives 2 full blocks of 3 slots plus a final row with one slot per most-frequent task. If there were enough other tasks to fill every idle slot, the answer would simply be len(tasks).
ABidle

Video Explanation

NeetCode — LeetCode 621