Skip to content

Single-Threaded CPU

MediumHeap / Priority Queue
Decode it first. Clues, constraints, pattern and plan before any code.

A CPU runs one task at a time. tasks[i] = [enqueue_time, processing_time] means task i becomes available at enqueue_time and takes processing_time units to finish. The CPU follows these rules:

  • If it is idle and no task is available, it waits for the next one.
  • If it is idle and tasks are available, it picks the one with the shortest processing time. On a tie, it picks the smallest index.
  • Once started, a task runs to completion. The CPU can start the next task immediately.

Return the order of task indices in which the CPU processes them.

tasks = [[1, 2], [2, 4], [3, 2], [4, 1]]  →  [0, 2, 3, 1]

At time 1 only task 0 is available, so it runs until 3. Tasks 1 and 2 are waiting; task 2 is shorter and runs until 5. Then task 3 (length 1) beats task 1 (length 4).

Constraints

  • 1 <= tasks.length <= 10^5
  • 1 <= enqueue_time, processing_time <= 10^9