Single-Threaded CPU
The key idea
(processingTime, index) gives that pick in O(log n); sort the tasks by enqueue time so you only add tasks that have actually arrived.Problem
You are given n tasks labeled 0 to n - 1 as a 2-D array tasks, where tasks[i] = [enqueueTime[i], processingTime[i]]. Each task i becomes available at time enqueueTime[i] and needs processingTime[i] units of work to finish.
The CPU has a single thread that runs the tasks one at a time using these rules:
- If the CPU is idle and no task is available, it stays idle.
- If the CPU is idle and there are available tasks, it picks the one with the shortest processingTime. Ties are broken by the smallest index.
- Once a task starts, it runs to completion without interruption.
- The moment a task finishes, the CPU can instantly start the next one.
Return the order in which the CPU processes the tasks, as a list of their indices.
Constraints
tasks.length == n1 <= n <= 10^51 <= enqueueTime[i], processingTime[i] <= 10^9
Examples
Complexity
Time: O(n log n) Space: O(n)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Heap / Priority Queue problems
- Find K Pairs with Smallest SumsMEDIUM
- Find Median from Data StreamHARD
- IPOHARD
- K Closest Points to OriginMEDIUM
- Kth Largest Element in a StreamEASY
- Kth Largest Element in an ArrayMEDIUM
- Last Stone WeightEASY
- Maximum Subsequence ScoreMEDIUM
- Meeting Rooms IIMEDIUM
- Meeting Rooms IIIHARD
- Merge k Sorted ListsHARD
- Minimum Interval to Include Each QueryHARD