Problem Description
You are given n tasks labeled from 0 to n-1, where each task is represented as [enqueueTime, processingTime]. When a task becomes available at its enqueueTime, it can be processed by a single-threaded CPU. The CPU always selects the available task with the shortest processing time (or the smallest index if tied) and runs it to completion. If no tasks are available, the CPU remains idle until a task can be processed. Return the order in which the CPU executes the tasks.
Key Insights
- Sort tasks by enqueueTime while preserving original indices.
- Use a min-heap (priority queue) to efficiently choose the task with the shortest processing time.
- If the heap is empty and tasks are yet to arrive, jump the current time to the next task's enqueueTime.
- Process tasks until all tasks have been scheduled.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting and heap operations. Space Complexity: O(n) for storing tasks and the heap.
Solution
We first augment each task with its original index and sort the tasks based on their enqueue times. We then use a min-heap to keep track of tasks that are available. At each step, we:
- Add all tasks available at the current time to the heap.
- If the heap is not empty, pop the task with the smallest processing time (using the original index as a tie breaker) and update the current time by its processing time.
- If the heap is empty, advance the current time to the next task's enqueue time. This process ensures that the CPU always processes the appropriate task and the order is maintained correctly.