Problem
You are given tasks, each a capital letter, and a cool-down n. The same task must be separated by at least n other units of time, which can be idle or a different task. Return the least number of units of time needed to finish every task.
Original: LeetCode 621: Task Scheduler.
Examples
Example 1
`tasks = ["A", "A", "A", "B", "B", "B"], n = 2``8`Example 2
`tasks = ["A", "C", "A", "B", "D", "B"], n = 1``6`Example 3
`tasks = ["A", "A", "A", "B", "B", "B"], n = 3``10`Constraints
1 <= tasks.length <= 10^4tasks[i]is an uppercase English letter.0 <= n <= 100
Hints
Hint 1
You can choose the order of tasks. n is the minimum gap between two executions of the same letter. If n is 0, the answer is just the number of tasks.
Hint 2
Scheduling with a cool-down is a greedy count of the most frequent item, or a simulation with a max-heap and a time queue.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Simulate slot by slot with a max-heap of remaining counts, pushing a finished task back after n idle or busy slots. That is correct and more general.
Optimal. Let maxCount be the highest frequency and extra be how many tasks have that frequency. The frame length is (maxCount - 1) * (n + 1) + extra. The answer is the maximum of that frame and the number of tasks.
Alternative. The heap simulation is useful if later follow-ups add per-task cool-downs or arrival times.
Complexity
- Time
- O(t)
O(t) time to count the tasks and O(1) extra space for a 26-letter alphabet, besides the input.
- Space
- O(1)
Code
from collections import Counter
def least_interval(tasks: list[str], n: int) -> int:
freq = Counter(tasks)
max_count = max(freq.values())
extra = sum(1 for c in freq.values() if c == max_count)
frames = (max_count - 1) * (n + 1) + extra
return max(frames, len(tasks))
if __name__ == "__main__":
assert least_interval(["A", "A", "A", "B", "B", "B"], 2) == 8
assert least_interval(["A", "C", "A", "B", "D", "B"], 1) == 6
assert least_interval(["A", "A", "A", "B", "B", "B"], 3) == 10
print("ok")public class TaskScheduler {
static int leastInterval(char[] tasks, int n) {
int[] freq = new int[26];
int maxCount = 0;
for (char t : tasks) {
freq[t - 'A']++;
if (freq[t - 'A'] > maxCount) maxCount = freq[t - 'A'];
}
int extra = 0;
for (int f : freq) if (f == maxCount) extra++;
int frames = (maxCount - 1) * (n + 1) + extra;
return Math.max(frames, tasks.length);
}
public static void main(String[] args) {
if (leastInterval(new char[] {'A', 'A', 'A', 'B', 'B', 'B'}, 2) != 8) throw new AssertionError();
if (leastInterval(new char[] {'A', 'C', 'A', 'B', 'D', 'B'}, 1) != 6) throw new AssertionError();
if (leastInterval(new char[] {'A', 'A', 'A', 'B', 'B', 'B'}, 3) != 10) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official samples: tasks ["A","A","A","B","B","B"] with n = 2 take 8 units (A B idle A B idle A B); the same tasks with n = 3 take 10 units; ["A","C","A","B","D","B"] with n = 1 take 6 units, which equals the number of tasks.
- When there is enough variety, idle slots disappear and the answer is tasks.length.
Follow-ups
- A max-heap simulation makes the same idea visible: you fill a window of n+1 slots with the current most frequent remaining tasks.
Interview script
"The cool-down is dictated by the most frequent task. I reserve (maxCount - 1) frames of length n+1, then add the tasks that share that maximum count. If that is still less than the number of tasks, other work already fills the idle gaps, so the answer is just the length of the list."
Source: LeetCode 621: Task Scheduler Source: Java SE 17 API: Math.max)
Sources
- LeetCode 215: Kth Largest Element in an Array
- Java SE 17 API: PriorityQueue
- LeetCode 703: Kth Largest Element in a Stream
- LeetCode 295: Find Median from Data Stream
- LeetCode 692: Top K Frequent Words
- LeetCode 23: Merge k Sorted Lists
- Python 3: heapq
- LeetCode 373: Find K Pairs with Smallest Sums
- LeetCode 767: Reorganize String
- LeetCode 621: Task Scheduler
- Java SE 17 API: Math.max)
Sources (2)
- LeetCode 621: Task Schedulerleetcode.com
- Java SE 17 API: Math.maxdocs.oracle.com