Skip to content
DSA Patterns
Menu
Language
GreedyLC #6215 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Mediumgreedy

Task Scheduler

Problem (restated)

CPU tasks labeled A-Z. Same letter needs cooldown n between runs. Any order; idle allowed. Min total units of time.

Intuition

Most frequent task forces (maxf-1) gaps of length n. Fill gaps with other tasks; leftover idles pad the schedule.

Approaches

Idle slots from max frequency

Unverified
Time O(n)Space O(1)

Idea. idles = max(0, empty, available); answer = tasks + idles. Multiple max-freq tasks shrink gap width.

Walkthrough. tasks=AAABBB, n=2 → 8.

Trade-offs. Priority queue simulation is O(n log 26); formula is O(n).

Solution
export function leastInterval(tasks: string[], n: number): number {
  const freq = Array(26).fill(0);
  let maxf = 0, maxCount = 0;
  for (const t of tasks) {
    const i = t.charCodeAt(0) - 65;
    freq[i]!++;
    if (freq[i]! > maxf) {
      maxf = freq[i]!;
      maxCount = 1;
    } else if (freq[i] === maxf) maxCount++;
  }
  const parts = maxf - 1;
  const partLen = n - (maxCount - 1);
  const empty = Math.max(0, parts * partLen);
  const available = tasks.length - maxf * maxCount;
  const idles = Math.max(0, empty - available);
  return tasks.length + idles;
}
export function leastInterval(tasks: string[], n: number): number {
  const freq = Array(26).fill(0);
  let maxf = 0, maxCount = 0;
  for (const t of tasks) {
    const i = t.charCodeAt(0) - 65;
    freq[i]!++;
    if (freq[i]! > maxf) {
      maxf = freq[i]!;
      maxCount = 1;
    } else if (freq[i] === maxf) maxCount++;
  }
  const parts = maxf - 1;
  const partLen = n - (maxCount - 1);
  const empty = Math.max(0, parts * partLen);
  const available = tasks.length - maxf * maxCount;
  const idles = Math.max(0, empty - available);
  return tasks.length + idles;
}

Template connection

The busiest task appears maxf times, and maxCount tasks share that count. Between those blocks sit maxf - 1 gaps of n - (maxCount - 1) slots. Slots filled by other tasks are not idle. The answer is the number of tasks plus those idle slots.

Reflection

  • Let f be the highest frequency and count the number of tasks that share it. The answer is max(length, (f - 1) * (n + 1) + count), which is the task length plus the idle slots those frames leave.
  • n = 0 leaves no idle time, so the answer is the length. One task answers 1.
  • The same letter f times needs n gaps between copies. A second letter at frequency f increases count.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Task scheduler: AAA BBB, cooldown n=2. Same letter needs 2 idle (or other) slots between runs.

A
0
A
1
A
2
B
3
B
4
B
5

n = 2

Key:Active rangeMatchSettledEliminated