mediumHeap / Priority Queue

Task Scheduler

Execute tasks in any order, one per time slot. Identical task letters must have at least n intervening slots. Idle slots are allowed. Find the shortest schedule length.

Work through the cases

3 examples

Input notation

Task letters separated by spaces on line 1; nonnegative cooldown n on line 2.

Expected result

The minimum number of slots.
Case 1

Input

A A A B B B
2

Expected output

8
Case 2

Input

A A B
0

Expected output

3
Case 3

Input

A A A
2

Expected output

7

These notes use simplified input/output notation. The linked platform defines the method signature and judge format.

FROM IDEA TO IMPLEMENTATION

Understand the approach.

Compare the documented approaches below. Brute force, better, and optimal versions appear where available; a direct exercise may need only one approach.

Identical tasks must be at least n apart. Simulating the timeline is unnecessary once the bottleneck task is known. The most frequent count x builds (x-1) full gaps plus s tasks of that count at the end. If the total number of tasks is larger, idle slots fill, so the answer is \max(m, (x-1)(n+1)+s).

class Solution {
    public int leastInterval(char[] tasks, int n) {
        int[] cnt = new int[26];
        int x = 0;
        for (char c : tasks) {
            c -= 'A';
            ++cnt[c];
            x = Math.max(x, cnt[c]);
        }
        int s = 0;
        for (int v : cnt) {
            if (v == x) {
                ++s;
            }
        }
        return Math.max(tasks.length, (x - 1) * (n + 1) + s);
    }
}

Reference code. Platform solutions may use supplied node types, imports, or collection libraries; foundational examples are complete programs.

Solutions adapted from Doocs / LeetCode contributors, licensed under CC BY-SA 4.0. Formatting changed; TypeScript versions converted to JavaScript. Supplemental implementations and approach notes added. Adapted solution material is available under the same license.