Task Scheduler
Find the fewest time units a CPU needs to run a list of tasks when copies of the same task must be kept apart.
A CPU must run a list of tasksn
Example 1
Output: 8
Explanation: A B idle A B idle A B.
Example 2
Output: 6
Example 3
Output: 16
Explanation: A B C A D E A F G A idle idle A idle idle A.
The Idea
Think of a coach running drills with a small team: after a player does a sprint, that player must rest for a while before sprinting again. The coach can send another player in the meantime, but if everyone is resting, the field stands empty for a minute. Here the players are letters, the rest is n
Walk through Example 1, with three A's, three B's and n = 2
Example 3 has six A's and one each of B to G. Whatever the order, the six A's need five gaps of at least 2 units between them, so the schedule takes at least 6 + 5 × 2 = 16 units. The other six tasks fill six of the ten gap units, and the remaining four are idle. So the letter that appears most often seems to decide the length. Can we count the units from that letter alone, without building the schedule?
Look at the picture below. Each schedule is cut into rows of n + 1 = 3
In Example 3, A appears 6 times, which gives rows 1 to 5 and a last row. Rows 1 to 5 are full, 3 units each, even when part of a row is idle. The last row holds only the final A, because nothing has to wait after it. That is 5 × 3 + 1 = 16.
In Example 1, B also appears 3 times, as often as A. Its final run comes after the final A, so the last row holds A and B: 2 × 3 + 2 = 8. The rows give the length directly: two full rows of 3, plus one cell in the last row for each letter tied for the top count.
Placing the most frequent letter first and fitting every other task into the cells around it, without trying other orders, is a greedy choice: each task takes a good spot right away and never moves again.
Solution Approach
Turning the rows into a count means settling four things: why trying every order is too slow, how big the frame of rows is, how the other tasks fit into it, and what happens when there are more tasks than cells.
Trying every order
Why not try each order of the tasks, add idle units where needed, and keep the shortest? Example 3 alone has 665,280 different orders of its twelve letters, and the number grows far faster than the list. The rows avoid that search, because their size follows from the counts.
The size of the frame
Call the count of the most frequent letter maxCountmaxCount - 1n + 1maxCounttasksWithMax
frame = (maxCount - 1) × (n + 1) + tasksWithMax
Fitting the other tasks in
Do the other tasks ever break a gap? A letter that is not tied for the top appears at most maxCount - 1
A letter with several copies goes down one column, one copy per row. Two cells in the same column are exactly n + 1
More tasks than cells
What if the tasks do not all fit into the frame? In Example 2, n = 0n = 2
Then the rows simply grow wider: A B C D, A B C D, A B E runs all 11 tasks with no idle unit. A wider row only puts more units between two copies of a letter, so the gaps still hold. No schedule can be shorter than the number of tasks, so the answer is the larger of frame
Java Solution
The method leastInterval
- First, count each letter in an array
of 26 cells, wherecount belongs to the lettercount[task - 'A'] . While counting, keep the largest count so far intask .maxCount - Then a second loop goes over the 26 counts and adds one to
for each letter whose count equalstasksWithMax .maxCount - Compute the size of the frame,
.frame = (maxCount - 1) * (n + 1) + tasksWithMax - Return the larger of
andframe .tasks.length
The mainn = 3n = 5
public class TaskScheduler {
public static int leastInterval(char[] tasks, int n) {
int[] count = new int[26];
int maxCount = 0;
for (char task : tasks) {
count[task - 'A']++;
maxCount = Math.max(maxCount, count[task - 'A']);
}
int tasksWithMax = 0;
for (int c : count) {
if (c == maxCount) {
tasksWithMax++; // tied for the top: one more cell in the last row
}
}
int frame = (maxCount - 1) * (n + 1) + tasksWithMax; // full rows, then the last row
return Math.max(frame, tasks.length); // more tasks than cells: no idle time
}
static void run(String tasks, int n) {
System.out.println(tasks + ", n = " + n + " -> " + leastInterval(tasks.toCharArray(), n));
}
public static void main(String[] args) {
run("AAABBB", 2);
run("AAABBB", 0);
run("AAAAAABCDEFG", 2);
run("AAABBBCCDDE", 2); // more tasks than cells in the frame
run("AAA", 3); // nothing to fill the gaps with
run("A", 5); // one task, the cooldown never matters
}
}
Running it prints:
AAABBB, n = 2 -> 8
AAABBB, n = 0 -> 6
AAAAAABCDEFG, n = 2 -> 16
AAABBBCCDDE, n = 2 -> 11
AAA, n = 3 -> 9
A, n = 5 -> 1
Look at the fourth line: AAABBBCCDDEMath.maxframe
The line AAA, n = 3 -> 9maxCount = 1n
Complexity
The work is one pass over the tasks and a fixed loop over 26 letters; the schedule itself is never built.
- Time: O(m) for m tasks, because the first loop reads each task once and the second loop always checks just 26 counts, whatever the cooldown
is.n - Space: O(1), because
has one cell per letter, 26 in all, and besides it the method keeps just three integers,count ,maxCount andtasksWithMax .frame
To build an actual schedule instead of only its length, a max-heap of remaining counts works, as