Time-Slice Scheduler
HardOnline Assessment
Compute when each job finishes on a shared processor that serves jobs in round-robin time slices.
jobs[i] = [arrival, duration] is a job that appears at time arrival and needs duration ticks of processor time in total. The processor serves one job at a time, in slices of at most quantum ticks, using a first-in-first-out ready queue:
- When the processor is idle and the queue is empty, time jumps to the next arrival. Jobs with the same arrival time enter the queue in input order (lower index first).
- The job at the front of the queue leaves the queue and runs for
min(quantum, its remaining time)ticks without interruption. - When a slice ends at time
t, first every job that has arrived by then (arrival <= t) is added to the back of the queue, in order of arrival time and then input index. Then, if the job that just ran still has time left, it goes to the back of the queue after them. So a job that arrives at exactly timetgoes in front of the job that was just preempted. - A job whose remaining time reaches 0 at the end of a slice finishes at that time, even if that slice was a full
quantum. It is not queued again. - The processor is idle only when the queue is empty and the next job has not arrived yet. Nothing else takes time (switching jobs is free).
Durations are large (up to 10^15), so simulating every slice one by one is too slow.
Input: jobs, a list of [arrival, duration] pairs, and quantum, an integer.
Output: a list with the finish time of each job, in the same order as jobs. If there are no jobs, return [].
Example 1
- Input:
- [[[0,5],[1,3],[2,2]],2]
- Output:
- [10,9,6]
- Explanation
- With quantum 2: job 0 runs 0-2. Job 2 arrives at exactly time 2, so it joins the queue before job 0 returns to it: the queue is job 1 (arrived at 1), job 2, job 0. Job 1 runs 2-4, job 2 runs 4-6 and finishes at 6, job 0 runs 6-8, job 1 runs 8-9 and finishes at 9, and job 0 finishes at 10.
Example 2
- Input:
- [[[0,4],[2,3],[4,1],[4,2]],2]
- Output:
- [6,10,7,9]
- Explanation
- Job 0 runs 0-2. Job 1 arrives at 2 and runs 2-4. Jobs 2 and 3 arrive at 4, and join in input order (2 before 3), ahead of job 1, which is preempted at 4 as well. Queue: 0, 2, 3, 1. Job 0 finishes at 6, job 2 at 7, job 3 runs 7-9 and finishes at 9 (using exactly one slice is a normal finish), and job 1 finishes at 10.
Example 3
- Input:
- [[[3,2],[3,3],[20,1],[7,4]],3]
- Output:
- [5,8,21,12]
- Explanation
- The processor idles until time 3, then job 0 (2 ticks) finishes at 5, shorter than the quantum. Job 1 (3 ticks) runs 5-8 and finishes at exactly the end of its slice; job 3 arrived at 7 and waits. Job 3 runs 8-11, is alone in the queue, and finishes at 12. The processor idles again until job 2 arrives at 20 and finishes at 21.
Constraints
- 0 ≤ jobs.length ≤ 100; each job is [arrival, duration] with 0 ≤ arrival ≤ 1012 and 1 ≤ duration ≤ 1015
- 1 ≤ quantum ≤ 106
- Jobs are not sorted by arrival time