TRT
Sign in
mediumCoreLeetCode#sort by arrival#min-heap by duration

Single-threaded CPU

Simulate a CPU that always runs the shortest available task, with a heap of tasks that have arrived.

The Runtime Theory Team1 min read
Taught inSift-up and sift-downPro — members onlyA heap inserts by appending at the end and swapping upward, and removes the minimum by moving the last item to the root and swapping downward. Each walks one path, so both are O(log n).
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

intasks = [[1, 2], [2, 4], [3, 2], [4, 1]]

out[0, 2, 3, 1]

intasks = [[7, 10], [7, 12], [7, 5], [7, 4], [7, 2]]

out[4, 3, 2, 0, 1]

Each task has an enqueue time and a processing time. A single-threaded CPU, whenever it is idle, starts the available task with the shortest processing time, breaking ties by smaller index. Return the order in which tasks are processed.

Before you code

Two orders are involved: tasks become available by enqueue time, and are chosen by (processing time, index). Sort by the first; keep a heap for the second.

Hints

  1. Sort task indexes by enqueue time.
  2. Keep a min-heap of (processing_time, index) for tasks that have arrived.
  3. When the heap is empty, jump the clock forward to the next arrival instead of ticking one unit at a time.
  4. After each task, push every task that has arrived by the new time.

Production & complexity notes

When solving Single-threaded CPU on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Sift-up and sift-down to reinforce the underlying pattern.

What it practices

A priority queue with tie-breaking, from Sift-up and sift-down. Real operating system schedulers use the same idea with richer priorities.

Not started

Sign in to save your learning progress.

Sign in to save