Task Scheduler II — LeetCode 2365 Python Solution

MediumArrayHash TableSimulation
Problem
#2365
Pattern
Hash Map
Reading time
2 min

The problem

You are given a 0-indexed array of positive integers tasks, representing tasks that need to be completed in order, where tasks[i] represents the type of the ith task. You are also given a positive integer space, which represents the minimum number of days that must pass after the completion of a task before another task of the same type can be performed.

Example

Input
tasks = [1,2,1,2,3,1], space = 3
Output
9
Explanation
One way to complete all tasks in 9 days is as follows:

Python solution

Python
class Solution:
    def taskSchedulerII(self, tasks: List[int], space: int) -> int:
        day = defaultdict(int)
        ans = 0
        for task in tasks:
            ans += 1
            ans = max(ans, day[task])
            day[task] = ans + space + 1
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the length of the array tasks auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2365. Task Scheduler II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2365. Task Scheduler II?
LeetCode 2365. Task Scheduler II is rated Medium on LeetCode.
What is the time complexity of LeetCode 2365. Task Scheduler II?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2365. Task Scheduler II?
The Python solution on this page uses O(n), where n is the length of the array tasks auxiliary space.
What topics does LeetCode 2365. Task Scheduler II cover?
LeetCode 2365. Task Scheduler II is tagged Array, Hash Table and Simulation 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.

Get Stealth Interview