Single-Threaded CPU - 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.
Input & Output
Example 1 — Basic Task Scheduling
$
Input:
tasks = [[1,2],[2,4],[3,2]]
›
Output:
[0,1,2]
💡 Note:
At time 1, only task 0 is available with processing time 2. At time 3, task 1 becomes available with processing time 4. At time 7, task 2 becomes available with processing time 2. Tasks are processed in the order they become available.
Example 2 — Priority by Processing Time
$
Input:
tasks = [[7,10],[7,12],[7,5],[7,4],[7,2]]
›
Output:
[4,3,2,0,1]
💡 Note:
All tasks are available at time 7. They are processed in order of shortest processing time: task 4 (2 time), task 3 (4 time), task 2 (5 time), task 0 (10 time), task 1 (12 time).
Example 3 — Mixed Timing
$
Input:
tasks = [[1,2],[2,1],[3,3]]
›
Output:
[0,2,1]
💡 Note:
Time 1: process task 0 (2 units) → finishes at time 3. Time 3: tasks 1 and 2 both available, task 1 has shorter processing time (1 < 3), so process task 1 first → finishes at time 4. Time 4: process task 2.
Constraints
- 1 ≤ tasks.length ≤ 105
- 1 ≤ enqueueTimei, processingTimei ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
Tasks with [enqueueTime, processingTime]: [[1,2], [2,4], [3,2]]
2
Process
CPU picks shortest processing time among available tasks
3
Output
Order of task execution: [0, 1, 2]
Key Takeaway
🎯 Key Insight: Sort tasks by enqueue time, then use a priority queue to always select the shortest processing time among available tasks
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code