#1834
Medium Algorithms Single threaded cpu
Array Sorting Heap (Priority Queue)
47.4% acceptance
Feb 25, 2026
3474
290
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.
Solution
Rust
Time O(n²)
Space O(n)
use std::collections::BinaryHeap;
use std::cmp::Reverse;
impl Solution {
pub fn get_order(tasks: Vec<Vec<i32>>) -> Vec<i32> {
let n = tasks.len();
// Index tasks by enqueue time; tuple (enqueue, processing, original_index)
let mut indexed: Vec<(i64, i64, usize)> = tasks.iter().enumerate()
.map(|(i, t)| (t[0] as i64, t[1] as i64, i))
.collect();
indexed.sort_unstable();
// min-heap: (processing_time, original_index)
let mut heap: BinaryHeap<Reverse<(i64, usize)>> = BinaryHeap::new();
let mut result = Vec::with_capacity(n);
let mut time: i64 = 0;
let mut idx = 0; // pointer into indexed
while result.len() < n {
// Add all tasks that are available at current time
while idx < n && indexed[idx].0 <= time {
heap.push(Reverse((indexed[idx].1, indexed[idx].2)));
idx += 1;
}
if heap.is_empty() {
// Jump to next available task
time = indexed[idx].0;
} else {
let Reverse((proc_time, orig_idx)) = heap.pop().unwrap();
result.push(orig_idx as i32);
time += proc_time;
}
}
result
}
}