Task Scheduler

Medium

Topics
ArrayGreedyHeapHash Table

Given a string tasks of uppercase-letter task types and a cooldown n (passed as the second value), each task takes one unit and identical tasks must be at least n units apart. Return the minimum number of units to finish all tasks.

Example 1

A0A1A2B3B4B5
Input:  tasks = "AAABBB", n = 2
Output: 8

Example 2

A0A1A2B3B4B5
Input:  tasks = "AAABBB", n = 0
Output: 6

Constraints

  • 1 <= tasks.length <= 10^4
  • tasks are uppercase English letters.
  • 0 <= n <= 100
Editorial — intuition, approach, complexity and pitfalls

Intuition

The most frequent task dictates the skeleton: place its copies with n gaps between them, forming (maxFreq - 1) frames of size (n + 1), then fill the last frame with the tasks that share the max frequency. If there are enough other tasks to fill all idle slots, the answer is just the total number of tasks.

Approach

  1. Count frequencies; find maxFreq and how many tasks have it (maxCount).
  2. Compute (maxFreq - 1) * (n + 1) + maxCount.
  3. The answer is the max of that and the total task count (when no idling is needed).

Dry Run

tasks "AAABBB", n = 2
Only the most frequent task matters, because it is the one forcing idle gaps.
  counts  {A: 3, B: 3}
  maxf = 3, and 2 tasks tie at that frequency
The frame: lay out maxf - 1 complete blocks of n + 1 slots, then a final row
holding one of each tied task.
  (maxf - 1) * (n + 1) + maxc  =  2 * 3 + 2  =  8
  len(tasks) = 6
answer max(6, 8) = 8     --  A B _ A B _ A B
The max against len(tasks) is not a safety net, it is a second regime. When n is
small there is no idle time at all and the answer is simply the number of tasks;
the frame formula then UNDERCOUNTS, because it only arranges the most frequent
tasks and ignores the rest. Measured: "AAABBB" with n = 0 gives 4 from the frame
alone where the answer is 6, and "AAABBBCCCDDD" with n = 1 gives 8 where the
answer is 12.
`maxc` -- how many tasks tie at the maximum frequency -- is what sizes the final
partial row. Here both A and B appear 3 times, so the last block holds two tasks
rather than one.
Nothing is ever actually scheduled. The answer is computed from three numbers, and
the schedule above is a reconstruction for the reader.

Complexity

  • Time — O(N): a single pass to count frequencies.
  • Space — O(1): at most 26 counts.

Common Pitfalls

  • Take the max with the total task count — with small n there may be no idle time at all.

Full Solution — all languages

class Solution:
    def leastInterval(self, s, k):
        cnt={}
        for ch in s: cnt[ch]=cnt.get(ch,0)+1
        maxf=max(cnt.values())
        maxc=sum(1 for f in cnt.values() if f==maxf)
        return max(len(s), (maxf-1)*(k+1)+maxc)
SensAI
Beta
Tap the mic to stop voice mode