heap
priority-queue
greedy

You are given a list of CPU tasks represented by uppercase letters. Each task takes exactly one interval, and the same letter must be separated by at least n idle or different-task intervals before it can run again. Return the minimum number of intervals needed to finish all tasks.

Input / output

  • Input: tasks: string[], n: int
  • Output: integer minimum number of intervals

Examples

  1. tasks = ["A","A","A","B","B","B"], n = 2 returns 8 because one optimal schedule is A, B, idle, A, B, idle, A, B.
  2. tasks = ["A","C","A","B","D","B"], n = 1 returns 6 because no idle time is needed.
  3. tasks = ["A","A","A","B","B","B"], n = 0 returns 6.

Constraints

  • 1 <= tasks.length <= 10^4
  • Each tasks[i] is a single uppercase English letter
  • 0 <= n <= 100

Target complexity

  • Aim for O(tasks.length) time and O(1) extra space beyond the fixed-size frequency table.

Hints

  1. The task with the highest frequency creates the tightest spacing requirement. Start by imagining that task placed first.
  2. Count how many tasks tie for the maximum frequency. They all occupy the last row of the same scheduling frame.

Follow-up How would you build an explicit schedule string if an interviewer asked you to print one valid timeline instead of only the minimum length?

Examples

Example 1

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

Example 2

Input: tasks = ["A","C","A","B","D","B"], n = 1
Output: 6

Example 3

Input: tasks = ["A","A","A","B","B","B"], n = 0
Output: 6
🔒 6 hidden

Running will execute all 9 cases, including 6 hidden ones.