Single-Threaded CPU Problem
Problem
You are given n
tasks labeled from 0
to n - 1
represented by a 2D integer array tasks
, where tasks[i] = [enqueueTimei, processingTimei]
means that the ith
task will be available to process at enqueueTimei
and will take processingTimei
to finish processing.
You have a single-threaded CPU that can process at most one task at a time and will act in the following way:
- If the CPU is idle and there are no available tasks to process, the CPU remains idle.
- If the CPU is idle and there are available tasks, the CPU will choose the one with the shortest processing time. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.
- Once a task is started, the CPU will process the entire task without stopping.
- The CPU can finish a task then start a new one instantly.
Return the order in which the CPU will process the tasks.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 – Sort and Min-Heap
Intuition
To always assign the CPU the shortest available task, we use a min-heap (priority queue) to efficiently select the task with the smallest processing time. However, since some short tasks may only become available later, we must first sort all tasks by their enqueue (start) time and only add them to the heap when they are available. This ensures the CPU never waits unnecessarily and always processes the optimal task.
Approach
- Preprocess Tasks:
- Attach the original index to each task for result tracking.
- Sort all tasks by their enqueue time.
- Simulate CPU Scheduling:
- Use a min-heap to store available tasks, ordered by processing time (and index for ties).
- Track the current time and iterate through the sorted tasks:
- Add all tasks whose enqueue time is less than or equal to the current time to the heap.
- If the heap is empty, fast-forward time to the next task’s enqueue time.
- Otherwise, pop the task with the shortest processing time from the heap, process it, and update the current time.
- Repeat until all tasks are processed.
- Build the Result:
- Record the order in which tasks are processed using their original indices.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n log n)
, since we sort the tasks and use heap operations for each task. - 🧺 Space complexity:
O(n)
, for storing the tasks and the heap.
Rust Code
|
|