Task Scheduler

Schedule tasks with a cooldown using a math identity on the most-frequent task.

Medium
Time O(n) Space O(1)
LeetCode
3 min read
intervals greedy math

Problem#

Each task takes one unit of time; identical tasks must be separated by at least n time units of cooldown. Return the minimum total time.

Examples#

  • tasks = ["A","A","A","B","B","B"], n = 28
  • tasks = ["A","C","A","B","D","B"], n = 16

Constraints#

  • 1 <= tasks.length <= 10^4, 0 <= n <= 100.

Hints#

Hint 1
The bottleneck is the most-frequent task. Other tasks fill its cooldown slots; idle slots fill the rest.

Approach#

Let maxFreq be the highest count and ties the number of tasks tied at that count. Frame: place maxFreq - 1 blocks of size n + 1 followed by ties trailing tasks. The answer is max(len(tasks), (maxFreq - 1) * (n + 1) + ties).

Solution#

Task Scheduler
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
int cnt[26] = {0};
for (char c : tasks) ++cnt[c - 'A'];
int maxFreq = *max_element(cnt, cnt + 26);
int ties = count(cnt, cnt + 26, maxFreq);
return max((int)tasks.size(), (maxFreq - 1) * (n + 1) + ties);
}
};

Editorial#

Picture the schedule as a grid: maxFreq rows of length n + 1 (one execution + n cooldown), with the last row possibly shorter. The most-frequent task fills the leftmost column; ties also each fill one column. Empty cells in the grid are idle. If the rest of the tasks can fit in the idle cells, total time is the grid size; otherwise it’s tasks.size() (no idleness needed). The max handles both cases.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.