Problem 489726 · medium · Level 04 Non-Linear Data Structures

Print Queue Order

heaps · event simulation · sorting · scheduling

A single printer receives jobs, where jobs[i] = [arrival, duration]. The printer handles one job at a time and never interrupts a job. Whenever it becomes free (including at the very start), it takes, among the jobs that have already arrived and are still waiting, the one with the shortest duration; if several tie, the one with the smallest index. A job that arrives at the very moment the printer becomes free counts as waiting. If no job is waiting, the printer idles until the next arrival.

Return the list of job indices in the order they are printed.

Examples

Input:  jobs = [[0, 4], [1, 3], [4, 1], [2, 1], [3, 3]]
Output: [0, 2, 3, 1, 4]
Explanation: job 0 runs from t=0 to t=4. Jobs 1 (3), 3 (1), 4 (3) and job 2 (1), which
             arrives exactly at t=4, are waiting. Jobs 2 and 3 tie on 1 and job 2 has the
             smaller index; then job 3; jobs 1 and 4 tie on 3, so job 1, then job 4.

Input:  jobs = [[8, 3], [0, 2], [8, 1], [3, 4]]
Output: [1, 3, 2, 0]
Explanation: job 1 runs until t=2; the printer idles until job 3 arrives at t=3 and runs it
             until t=7; it idles again until t=8, then job 2 (1) goes before job 0 (3).

Constraints

  • 1 <= len(jobs) <= 10**5, 0 <= arrival <= 10**9, 1 <= duration <= 10**4
  • Target complexity: O(n log n).

Goals

  • Sort jobs by arrival and release them into a heap as the clock advances
  • Pick the shortest available job with a deterministic tie-break
  • Jump the clock forward when the printer is idle
Starting Python…