1797. Preemptive Shortest First

Medium3.5 points estimatedHeapSimulationSorting

A single processor handles n print jobs. Job i is submitted at time arrivals[i] and needs durations[i] units of work. The processor always works on the submitted, unfinished job with the least work remaining (the smaller index wins a tie); a newly submitted job may therefore interrupt the one being processed, which later resumes with its remaining work. If no submitted job is unfinished, the processor idles until the next submission.

Return an int[] with the indices of the jobs in the order in which they finish. The clock can exceed 2^31, so use 64-bit arithmetic. Sorting by arrival plus a heap of (remaining, index) gives O(n log n) time and O(n) space.

Example 1

Input:
arrivals = [0,1,2], durations = [8,4,1]
Output:
[2,1,0]
Explanation:

Job 0 starts, job 1 (4 units) interrupts it at time 1 because 4 < 7, and job 2 (1 unit) interrupts at time 2; they finish in the order 2, 1, 0.

Example 2

Input:
arrivals = [5,0], durations = [2,3]
Output:
[1,0]
Explanation:

Job 1 runs from 0 to 3, then the processor idles until job 0 arrives at 5, so the order is 1, 0.

Constraints

1 ≤ n ≤ 105

0 ≤ arrivals[i] ≤ 109

1 ≤ durations[i] ≤ 104

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,600 msC++ 1,150 msJava 2,300 msJavaScript 2,300 msTypeScript 2,300 ms

Expected complexity

Time
O(n log n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…