Problem 489726 · medium · Phase 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. 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 = [[1, 2], [2, 4], [3, 2], [4, 1]]
Output: [0, 2, 3, 1]
Explanation: t=1 only job 0 has arrived; it runs until t=3. Jobs 1 (4) and 2 (2) are waiting:
             job 2 runs until t=5. Now jobs 1 (4) and 3 (1) wait: job 3, then job 1.

Input:  jobs = [[7, 10], [7, 12], [7, 5], [7, 4], [7, 2]]
Output: [4, 3, 2, 0, 1]
Explanation: all arrive together, so they simply run shortest first.

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…