Schedule Fixed-Order Tasks with a Cooldown
CoinbaseSoftware Engineer · OnsiteLast updated
Calculate the total days required to run a sequence of tasks in a strict, fixed order where identical tasks must be separated by a specified cooldown period.
Problem Statement
You are given an array of integers tasks representing task IDs that must be processed strictly in the order they appear, and an integer cooldown.
Each task takes exactly one day to complete, and at most one task can be performed per day. Once a task with ID x is completed on day d, another task with the same ID x cannot be scheduled until at least cooldown calendar days have elapsed. That is, the earliest subsequent day that task x can be executed is d + cooldown + 1.
Days where no task can be performed are considered idle days. Return the total number of calendar days needed to execute all tasks in the given order.
Interface
def min_days_to_complete_tasks(tasks: list[int], cooldown: int) -> int:
pass
Examples
Example 1
Input: tasks = [1, 2, 1, 3, 2, 1], cooldown = 2
Output: 7
Explanation:
- Day 1: Execute task 1 (last ran day 1)
- Day 2: Execute task 2 (last ran day 2)
- Day 3: Idle (task 1 cannot run until day 1 + 2 + 1 = 4)
- Day 4: Execute task 1 (last ran day 4)
- Day 5: Execute task 3 (last ran day 5)
- Day 6: Execute task 2 (earliest allowed was day 2 + 2 + 1 = 5 <= 6)
- Day 7: Execute task 1 (earliest allowed was day 4 + 2 + 1 = 7 <= 7)
Total days taken: 7.
Example 2
Input: tasks = [1, 1, 1], cooldown = 3
Output: 9
Explanation:
- Day 1: Execute task 1
- Days 2-4: Idle
- Day 5: Execute task 1
- Days 6-8: Idle
- Day 9: Execute task 1
Total days taken: 9.
Constraints
1 <= len(tasks) <= 2 * 10^50 <= tasks[i] <= 10^90 <= cooldown <= 10^5
Edge Cases
cooldown = 0: Tasks execute back-to-back without any idle days, takinglen(tasks)days.- All tasks distinct: No idle days are ever needed regardless of
cooldownvalue.
Hints
Hint 1
Because the order is strictly fixed, each task's earliest start day depends only on the previous day and the last time that specific task ID was run.
Hint 2
Use a hash map to store the most recent day each task ID was executed.
Hint 3
For each task, update the current day to max(current_day + 1, last_seen[task] + cooldown + 1).
Follow-up questions
- How would you clean up the hash map in a real-time streaming environment to prevent unbounded memory growth?
- How would you adapt the solution if each task type had its own specific cooldown duration instead of a global cooldown?
- What changes would be necessary if tasks could be executed out of order to minimize the total completion time?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.