1699. Time Slice Scheduler

Medium3.5 points estimatedQueueSimulationArray

A single CPU shares its time between jobs using round-robin scheduling with time slice q. Job i arrives at time arrival[i] (the array is non-decreasing; jobs with equal arrival times queue in index order) and needs burst[i] units of CPU. The CPU always takes the job at the front of the ready queue and runs it for min(q, remaining) units. Jobs that arrive while the slice runs, or exactly when it ends, join the queue before the preempted job is put back at the end. If the queue is empty the CPU idles until the next arrival. Return a long[] with the completion time of every job in input order. The total number of slices is at most 10^6.

Example 1

Input:
arrival = [0,1,2], burst = [5,3,1], q = 2
Output:
[9,8,5]
Explanation:

P0 runs 0-2, then P1 (arrived at 1) and P2 (arrived at 2) are queued ahead of it; the order of slices is P0, P1, P2, P0, P1, P0 and the clock ends at 9, 8 and 5.

Example 2

Input:
arrival = [0,10], burst = [3,2], q = 5
Output:
[3,12]
Explanation:

P0 finishes at 3, the CPU idles until time 10, and P1 then finishes at 12.

Example 3

Input:
arrival = [0,2,2], burst = [4,2,3], q = 2
Output:
[8,4,9]
Explanation:

P1 and P2 arrive exactly when the first slice ends, so they join the queue before P0 is re-queued: slices P0, P1 (done at 4), P2, P0 (done at 8), P2 (done at 9).

Constraints

1 ≤ n ≤ 500

0 ≤ arrival[i] ≤ 109, non-decreasing

1 ≤ burst[i] ≤ 104

1 ≤ q ≤ 104

The total number of slices is at most 106.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(S + n) where S is the number of slices
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…