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 tasks, where each task is a capital letter from A to Z and takes one time unit. Between two runs of the same letter, at least n other units must pass. In any unit the CPU runs one task or stays idle, and the tasks may run in any order. Return the fewest units needed to run them all.

Example 1
Input: tasks = ["A", "A", "A", "B", "B", "B"], n = 2
Output: 8
Explanation: A B idle A B idle A B.
Example 2
Input: tasks = ["A", "A", "A", "B", "B", "B"], n = 0
Output: 6
Example 3
Input: tasks = ["A", "A", "A", "A", "A", "A", "B", "C", "D", "E", "F", "G"], n = 2
Output: 16
Explanation: A B C A D E A F G A idle idle A idle idle A.
Solution

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 units, and an empty minute is an idle unit.

Walk through Example 1, with three A's, three B's and n = 2. Run A, then B. In the third unit, A has rested only one unit and B none, so the CPU has to stay idle. Then A and B again, another idle unit, and a last A and B: 8 units, two of them idle.

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 units, and each row starts with an A, so two A's are always a full row apart.

Both schedules laid out in rows of n + 1 = 3 units, each row starting with A. Example 1: row 1 is A B idle, row 2 is A B idle, and the last row is A B, 2 × 3 + 2 = 8 units. Example 3: rows 1 to 3 hold A with B and C, D and E, F and G, rows 4 and 5 are A idle idle, and the last row is A alone, 5 × 3 + 1 = 16 units.

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 maxCount. That letter needs maxCount - 1 full rows of n + 1 units, and then the last row. The number of letters tied at maxCount, kept in tasksWithMax, is the length of the last row. All of these cells together form the frame:

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 times, fewer than there are rows. So its copies can go into different rows, one free cell per row. In Example 3, B to G each appear once and simply take the six free cells of rows 1 to 3.

A letter with several copies goes down one column, one copy per row. Two cells in the same column are exactly n + 1 units apart, just like the A's at the start of each row. The free cells left over stay idle.

More tasks than cells

What if the tasks do not all fit into the frame? In Example 2, n = 0, so the frame is 2 × 1 + 2 = 4 cells, but there are 6 tasks. Or take three A's, three B's, two C's, two D's and one E with n = 2: a frame of 2 × 3 + 2 = 8 cells for 11 tasks.

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 and the number of tasks.

Java Solution

The method leastInterval only counts and never builds the schedule:

  1. First, count each letter in an array count of 26 cells, where count[task - 'A'] belongs to the letter task. While counting, keep the largest count so far in maxCount.
  2. Then a second loop goes over the 26 counts and adds one to tasksWithMax for each letter whose count equals maxCount.
  3. Compute the size of the frame, frame = (maxCount - 1) * (n + 1) + tasksWithMax.
  4. Return the larger of frame and tasks.length.

The main method runs the three examples, the list with more tasks than cells, three A's with n = 3, and a single task with n = 5.

Java
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:

Output
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: AAABBBCCDDE takes 11 units, one per task. Its frame has only 8 cells, so Math.max returns the task count. A version that returns frame alone prints 8 for this line and 4 for Example 2, both shorter than the number of tasks to run.

The line AAA, n = 3 -> 9 has nothing to fill the gaps, so the schedule is A, three idle units, A, three idle units, A. On the last line, a single A gives maxCount = 1, so there are no full rows and the answer is 1, whatever the value of n.

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 n is.
  • Space: O(1), because count has one cell per letter, 26 in all, and besides it the method keeps just three integers, maxCount, tasksWithMax and frame.

To build an actual schedule instead of only its length, a max-heap of remaining counts works, as Reorganize String does to build its arrangement.