#2365
Task Scheduler II
MediumArrayHash TableSimulationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a hashmap to track the last day a task was completed, allowing us to efficiently calculate the required breaks without simulating each day. This reduces unnecessary checks and speeds up the process.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a day counter and a hashmap to track the last completion day of each task type.
- 2Step 2: Iterate through the tasks array.
- 3Step 3: For each task, check when it was last completed and calculate the necessary breaks to ensure the 'space' requirement is met.
- 4Step 4: Update the day counter and the last completion day for the task.
solution.py10 lines
1def minDays(tasks, space):
2 days = 0
3 last_completed = {}
4 for task in tasks:
5 days += 1
6 if task in last_completed:
7 days += max(0, space - (days - last_completed[task]))
8 last_completed[task] = days
9 return days
10ℹ
Complexity note: The complexity is linear because we only make a single pass through the tasks array, and the hashmap operations (insert and lookup) are average O(1).
- 1Using a hashmap to track the last completion day of tasks allows for efficient checking of whether breaks are needed.
- 2Taking breaks as late as possible helps minimize the total number of days.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.