Skip to the code
cf.
+25 XP

#399 Shortest Job First Queue

medium

A single web worker processes image-resize jobs one at a time. Job i arrives at time tasks[i][0] and takes tasks[i][1] time units. Whenever the worker is free, it starts the shortest job that has already arrived (smaller index on ties). If nothing has arrived yet, it waits for the next arrival. A job runs to the end once started.

Write processingOrder(tasks) that returns the job indexes in the order they are started. The worker is free at time 0.

Example 1

Input: tasks = [[0,3],[1,9],[2,4],[3,1]]
Output: [0,3,2,1]

Job 0 runs until 3. Then jobs 1, 2, 3 are waiting, and 3 is shortest, then 2, then 1.

Example 2

Input: tasks = [[5,2],[5,2]]
Output: [0,1]

Same arrival and length, so the smaller index goes first.

Constraints

  • 1 <= tasks.length <= 10^5
  • 0 <= arrive <= 10^9
  • 1 <= length <= 10^9
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).