KatInterview

621. Task Scheduler

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Mathematical Formula

This problem asks for the minimum time to schedule tasks with a cooldown period. While a simulation using a priority queue can work, a more direct and efficient approach involves a mathematical formula derived from analyzing the schedule's structure.

Solution

Task Scheduler in Python

import collections

class Solution:
    def leastInterval(self, tasks: List[str], n: int) -> int:
        # Step 1: Count the frequency of each task.
        # collections.Counter is a handy way to do this.
        if not tasks:
            return 0
        task_counts = collections.Counter(tasks)

        # Step 2: Find the maximum frequency.
        # This task will be the bottleneck for the schedule.
        max_freq = max(task_counts.values())

        # Step 3: Count the number of tasks that have the maximum frequency.
        # These tasks will form the last 'row' of our conceptual schedule grid.
        num_max_freq_tasks = 0
        for count in task_counts.values():
            if count == max_freq:
                num_max_freq_tasks += 1
        
        # Step 4: Calculate the total time based on the formula.
        # The schedule is determined by the most frequent task(s).
        # Imagine (max_freq - 1) full blocks of (task + n idles/other tasks),
        # followed by the last occurrences of all max-frequency tasks.
        # Length of each full block is (n + 1).
        # Total length = (number of full blocks) * (block length) + (length of last block)
        time = (max_freq - 1) * (n + 1) + num_max_freq_tasks

        # Step 5: The total time must be at least the number of tasks.
        # This handles cases where there are no idle slots needed because
        # we have enough different tasks to fill the time.
        return max(len(tasks), time)

Task Scheduler in Java

class Solution {
    public int leastInterval(char[] tasks, int n) {
        // Step 1: Count the frequency of each task.
        // Since tasks are 'A'-'Z', an array of size 26 is sufficient.
        int[] counts = new int[26];
        for (char task : tasks) {
            counts[task - 'A']++;
        }

        // Step 2: Find the maximum frequency.
        int max_freq = 0;
        for (int count : counts) {
            max_freq = Math.max(max_freq, count);
        }

        // Step 3: Count the number of tasks with the maximum frequency.
        int num_max_freq_tasks = 0;
        for (int count : counts) {
            if (count == max_freq) {
                num_max_freq_tasks++;
            }
        }

        // Step 4: Calculate the time based on the formula.
        // The schedule length is determined by the most frequent tasks.
        // It consists of (max_freq - 1) full blocks, where each block has
        // one of the high-frequency tasks followed by n slots for other tasks or idles.
        // The total time for these blocks is (max_freq - 1) * (n + 1).
        // The final part of the schedule consists of the last occurrences of all
        // the most frequent tasks, which is num_max_freq_tasks.
        int time = (max_freq - 1) * (n + 1) + num_max_freq_tasks;

        // Step 5: The result is the maximum of the calculated time and the total number of tasks.
        // This covers the case where no idle slots are needed because there are enough
        // different tasks to fill the cooldown periods.
        return Math.max(tasks.length, time);
    }
}

Task Scheduler in C++

class Solution {
public:
    int leastInterval(vector<char>& tasks, int n) {
        // Step 1: Count the frequency of each task.
        // Since tasks are 'A'-'Z', a vector of size 26 is sufficient.
        vector<int> counts(26, 0);
        for (char task : tasks) {
            counts[task - 'A']++;
        }

        // Step 2: Find the maximum frequency.
        int max_freq = 0;
        for (int count : counts) {
            max_freq = max(max_freq, count);
        }

        // Step 3: Count the number of tasks that have the maximum frequency.
        int num_max_freq_tasks = 0;
        for (int count : counts) {
            if (count == max_freq) {
                num_max_freq_tasks++;
            }
        }

        // Step 4: Calculate the time based on the formula.
        // The schedule length is determined by the most frequent tasks.
        // It consists of (max_freq - 1) full blocks, where each block has
        // one of the high-frequency tasks followed by n slots for other tasks or idles.
        // The total time for these blocks is (max_freq - 1) * (n + 1).
        // The final part of the schedule consists of the last occurrences of all
        // the most frequent tasks, which is num_max_freq_tasks.
        int time = (max_freq - 1) * (n + 1) + num_max_freq_tasks;

        // Step 5: The result is the maximum of the calculated time and the total number of tasks.
        // This covers the case where no idle slots are needed because there are enough
        // different tasks to fill the cooldown periods.
        // Cast tasks.size() to int to ensure correct comparison.
        return max((int)tasks.size(), time);
    }
};

Task Scheduler in TypeScript

function leastInterval(tasks: string[], n: number): number {
    // Step 1: Count the frequency of each task.
    // Using an object as a frequency map.
    const counts: { [key: string]: number } = {};
    for (const task of tasks) {
        counts[task] = (counts[task] || 0) + 1;
    }

    const frequencies = Object.values(counts);
    if (frequencies.length === 0) {
        return 0;
    }

    // Step 2: Find the maximum frequency.
    const max_freq = Math.max(...frequencies);

    // Step 3: Count the number of tasks with the maximum frequency.
    let num_max_freq_tasks = 0;
    for (const freq of frequencies) {
        if (freq === max_freq) {
            num_max_freq_tasks++;
        }
    }

    // Step 4: Calculate the time based on the formula.
    // The schedule length is determined by the most frequent tasks.
    // It consists of (max_freq - 1) full blocks, where each block has
    // one of the high-frequency tasks followed by n slots for other tasks or idles.
    // The total time for these blocks is (max_freq - 1) * (n + 1).
    // The final part of the schedule consists of the last occurrences of all
    // the most frequent tasks, which is num_max_freq_tasks.
    const time = (max_freq - 1) * (n + 1) + num_max_freq_tasks;

    // Step 5: The result is the maximum of the calculated time and the total number of tasks.
    // This covers the case where no idle slots are needed because there are enough
    // different tasks to fill the cooldown periods.
    return Math.max(tasks.length, time);
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.