621. Task Scheduler
Asked at 23Amazon62Apple49Microsoft46Google41Meta39Bloomberg34Roblox80Docusign74Zeta74Nutanix71Okta71MathWorks66tcs61Snowflake59Coupang58Oracle52Rubrik50Walmart Labs43Goldman Sachs36Uber35TikTok35Infosys30LinkedIn20
Problem
tasks are letters, each taking one time unit. Two runs of the same letter must be separated by at least n units; in each unit the CPU runs one task or stays idle, and tasks can run in any order. Return the minimum number of units needed for all tasks.
Example: tasks = ["A","A","A","B","B","B"], n = 2 → 8 (A B idle A B idle A B)
Constraints: up to 10⁴ tasks; 0 ≤ n ≤ 100.
The most frequent task(s) dictate the frame: (maxf − 1) full blocks of size n + 1, plus one slot per task tied at maxf. If there are more tasks than slots, no idle is needed → answer is len(tasks).
tasks A A A B B B, n=2 maxf=3, tied=2
A B _ | A B _ | A B (3-1)*(2+1) + 2 = 8
Complexity: O(n).
class Solution:
def leastInterval(self, tasks: List[str], n: int) -> int:
cnt = Counter(tasks).values()
maxf = max(cnt)
tied = sum(1 for c in cnt if c == maxf)
return max(len(tasks), (maxf - 1) * (n + 1) + tied)
assert Solution().leastInterval(["A", "A", "A", "B", "B", "B"], 2) == 8
assert Solution().leastInterval(["A", "C", "A", "B", "D", "B"], 1) == 6
assert Solution().leastInterval(["A", "A", "A", "B", "B", "B"], 3) == 10
class Solution {
public int leastInterval(char[] tasks, int n) {
int[] cnt = new int[26];
int maxf = 0, tied = 0;
for (char t : tasks) maxf = Math.max(maxf, ++cnt[t - 'A']);
for (int c : cnt) if (c == maxf) tied++;
return Math.max(tasks.length, (maxf - 1) * (n + 1) + tied);
}
}
func leastInterval(tasks []byte, n int) int {
var cnt [26]int
for _, t := range tasks {
cnt[t-'A']++
}
maxf, tied := 0, 0
for _, c := range cnt {
if c > maxf {
maxf, tied = c, 1
} else if c == maxf {
tied++
}
}
// (maxf-1) full frames of n+1 slots, plus the tasks tied for most frequent
return max(len(tasks), (maxf-1)*(n+1)+tied)
}