Problem Description
Given an ordered array of tasks where each task is represented by its type, and a positive integer space that represents the minimum number of days that must pass after completing a task before the same task type can be performed again, determine the minimum number of days needed to complete all tasks. Each day, you must either complete the next task in order or take a break.
Key Insights
- Tasks must be executed in the given order.
- When a task is scheduled, if the same type was executed recently, you may have to wait (simulate breaks) to satisfy the space requirement.
- Use a hash table (dictionary) to track the next available day for each task type.
- For each task, compute the day it can be executed by considering current day and the task’s availability from previous occurrences.
Space and Time Complexity
Time Complexity: O(n), where n is the number of tasks.
Space Complexity: O(u), where u is the number of unique task types.
Solution
We simulate the process of executing tasks day by day. For each task, we check if it was executed before. If so, we compare the current day with the next available day for that task type. If the current day is less than the next available day, we simulate waiting by jumping to that day. Then, update the next available day for that task type as the current day plus space plus one. This approach efficiently ensures that no subsequent task of the same type is scheduled before the required waiting period.