Task Scheduler II - Problem

You're managing a project workflow where tasks must be completed in a specific order, but there's a cooldown period between tasks of the same type.

Given an array tasks where tasks[i] represents the type of the i-th task that must be completed, and an integer space representing the minimum number of days that must pass after completing a task before another task of the same type can be performed.

Each day you can either:

  • Complete the next task from the tasks array (if allowed)
  • Take a break (if the next task type is still in cooldown)

Goal: Return the minimum number of days needed to complete all tasks while respecting the cooldown constraints.

Example: tasks = [1,2,1,2,3,1], space = 3
Day 1: Complete task 1
Day 2: Complete task 2
Day 3: Break (task 1 still in cooldown)
Day 4: Break (task 1 still in cooldown)
Day 5: Break (task 1 still in cooldown)
Day 6: Complete task 1
...and so on

Input & Output

example_1.py โ€” Basic Case
$ Input: tasks = [1,2,1,2,3,1], space = 3
โ€บ Output: 9
๐Ÿ’ก Note: Day 0: Task 1, Day 1: Task 2, Day 2-4: Break (Task 1 cooldown), Day 5: Task 1, Day 6-8: Break (Task 2 cooldown), Day 9: Task 2, etc. Total 9 days needed.
example_2.py โ€” No Conflicts
$ Input: tasks = [5,8,8,5], space = 2
โ€บ Output: 6
๐Ÿ’ก Note: Day 0: Task 5, Day 1: Task 8, Day 2: Break, Day 3: Task 8, Day 4: Break, Day 5: Task 5. The space=2 requirement causes breaks between repeated tasks.
example_3.py โ€” Large Space
$ Input: tasks = [1,1,1], space = 4
โ€บ Output: 11
๐Ÿ’ก Note: Day 0: Task 1, Days 1-4: Break, Day 5: Task 1, Days 6-9: Break, Day 10: Task 1. With space=4, we need 4 break days between each task 1.

Constraints

  • 1 โ‰ค tasks.length โ‰ค 105
  • 1 โ‰ค tasks[i] โ‰ค 109
  • 0 โ‰ค space โ‰ค tasks.length
  • Tasks must be completed in the given order

Visualization

Tap to expand
๐Ÿญ Factory Assembly Line with Machine CooldownEach machine needs rest time before it can be used againMachine 1Last used:Day 0Machine 2Last used:Day 1Machine 3Last used:NeverProduction Timeline (Space = 3 days)M1Day 0M2Day 1โธDay 2โธDay 3โธDay 4M1Day 5โœ… Machine 1 ready after 3-day cooldown
Understanding the Visualization
1
Machine Usage Tracking
Keep a log of when each machine was last used
2
Check Availability
Before using a machine, check if enough cooldown time has passed
3
Decision Making
If machine is ready, use it and update the log. If not, wait one day
4
Process Completion
Continue until all products in the queue are manufactured
Key Takeaway
๐ŸŽฏ Key Insight: Instead of scanning all previous days, we only need to remember the last usage day of each machine type for O(1) cooldown checks
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
42.8K Views
Medium Frequency
~15 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen