Skip to content
Decoder

Single-Threaded CPU

Medium

Problem

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.

Example 1

Input
tasks = [[1, 2], [2, 4], [3, 2], [4, 1]]
Output
[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

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.