Task Scheduler

Sanjeev SharmaSanjeev Sharma
2 min read

Advertisement

Problem

Given tasks and cooldown n, return minimum intervals to finish all tasks. Idle cycles are allowed.

Two approaches:

  1. Math formula: max(sum, (max_freq - 1) * (n + 1) + count_of_max_freq)
  2. Simulation with max-heap

Approach 1 — Formula (O(n))

max_freq = max frequency
count_max = number of tasks with max_freq
answer = max(total_tasks, (max_freq - 1) * (n + 1) + count_max)

Solutions

// C — formula
int leastInterval(char* tasks, int n, int tasksSize) {
    int freq[26] = {0};
    for (int i = 0; i < tasksSize; i++) freq[tasks[i]-'A']++;
    int maxF = 0, countMax = 0;
    for (int i = 0; i < 26; i++) if (freq[i] > maxF) maxF = freq[i];
    for (int i = 0; i < 26; i++) if (freq[i] == maxF) countMax++;
    int ans = (maxF - 1) * (n + 1) + countMax;
    return ans > tasksSize ? ans : tasksSize;
}
// C++
int leastInterval(vector<char>& tasks, int n) {
    vector<int> freq(26, 0);
    for (char t : tasks) freq[t-'A']++;
    int maxF = *max_element(freq.begin(), freq.end());
    int countMax = count(freq.begin(), freq.end(), maxF);
    return max((int)tasks.size(), (maxF - 1) * (n + 1) + countMax);
}
// Java
public int leastInterval(char[] tasks, int n) {
    int[] freq = new int[26];
    for (char t : tasks) freq[t-'A']++;
    int maxF = 0;
    for (int f : freq) maxF = Math.max(maxF, f);
    int countMax = 0;
    for (int f : freq) if (f == maxF) countMax++;
    return Math.max(tasks.length, (maxF - 1) * (n + 1) + countMax);
}
// JavaScript
function leastInterval(tasks, n) {
    const freq = new Array(26).fill(0);
    for (const t of tasks) freq[t.charCodeAt(0) - 65]++;
    const maxF = Math.max(...freq);
    const countMax = freq.filter(f => f === maxF).length;
    return Math.max(tasks.length, (maxF - 1) * (n + 1) + countMax);
}
# Python — formula
from collections import Counter

def leastInterval(tasks, n):
    freq = Counter(tasks)
    max_f = max(freq.values())
    count_max = sum(1 for f in freq.values() if f == max_f)
    return max(len(tasks), (max_f - 1) * (n + 1) + count_max)

Complexity

  • Time: O(n)
  • Space: O(1) — 26-letter alphabet

Key Insight

The most frequent task determines the skeleton: (max_f - 1) full cycles of (n+1) slots, plus the final row of all tasks with max frequency. If we have enough tasks to fill all idle slots, answer is just total tasks.

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro