#621

Task Scheduler

Medium Greedy counting

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

CPU tasks are letters; the same letter needs at least n intervals between runs. Each interval runs one task or idles. Return the minimum number of intervals.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: least time to run tasks when the same task needs n gaps between runs.

Why this works: the most frequent task sets a frame: (max - 1) blocks of size n + 1, plus one slot for each task tied at max. If there are more tasks than slots, no idling is needed.

Example: A A A B B B, n = 2

(3 - 1) × 3 + 2 = 8A B _ A B _ A B

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Forgetting the max with tasks.length, which gives too small an answer when there's no idle time.

Solve on LeetCode ↗
Complexity
  • Time: O(m), m = number of tasks.
  • Space: O(26).
Topic: Heaps & Priority Queue
🎬 Episodes 64–68: video coming soon