MediumNo. 0621

Task Scheduler — LeetCode 621 Python Solution

Topics
Greedy, Array, Hash Table, Counting, Sorting, Heap (Priority Queue)
On study lists
NeetCode 150 and Grind 75
Reading time
2 min

The problem

You are given an array of CPU tasks, each labeled with a letter from A to Z, and a number n. Each CPU interval can be idle or allow the completion of one task.

Python solution

PythonSolution
class Solution:
    def leastInterval(self, tasks: List[str], n: int) -> int:
        cnt = Counter(tasks)
        x = max(cnt.values())
        s = sum(v == x for v in cnt.values())
        return max(len(tasks), (x - 1) * (n + 1) + s)

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 621. Task Scheduler is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
2365Task Scheduler IIMedium
1054Distant BarcodesMedium
0347Top K Frequent ElementsMedium
0632Smallest Range Covering Elements from K ListsHard
0692Top K Frequent WordsMedium
0767Reorganize StringMedium

Frequently asked questions

How hard is LeetCode 621. Task Scheduler?

LeetCode 621. Task Scheduler is rated Medium on LeetCode.

What is the time complexity of LeetCode 621. Task Scheduler?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 621. Task Scheduler?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 621. Task Scheduler cover?

LeetCode 621. Task Scheduler is tagged Greedy, Array, Hash Table, Counting, Sorting and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.