~/problems / Heaps / Heap scheduling (deadlines, leases)

Single-Threaded CPU

medium ~25 min

A single CPU processes jobs one at a time without interruption. Job i is given as [ready_i, length_i]: it becomes available at time ready_i and takes length_i time units once started.

The CPU follows these rules:

  • When it's idle and no job is available, it waits until the next job becomes available.
  • When it's idle and at least one job is available, it starts the available job with the shortest length, breaking ties by the smallest index.
  • Once it finishes a job it immediately picks the next one by the same rule; jobs that became available at or before that moment are eligible.

Write get_order(jobs) that returns the list of job indices in the order the CPU runs them.

get_order([[2, 3], [0, 5], [1, 1], [6, 2]])   # [1, 2, 3, 0]
# t=0: only job1 is ready -> runs 0..5. At 5, jobs 0 (len 3) and 2 (len 1) are ready -> job2 5..6.
# At 6, jobs 0 (len 3) and 3 (len 2) -> job3 6..8, then job0.
get_order([[4, 2], [4, 2], [4, 1]])           # [2, 0, 1]

Constraints: up to 100,000 jobs; times and lengths up to 10^9.

Re-scanning every pending job at each step is O(n²) and too slow for the tests; aim for O(n log n). Total elapsed time can pass 2**31, so use 64-bit integers for it in C++/Java.

Show hint

process jobs in order of ready time, and keep the jobs that are already available in a structure that hands you the shortest one (ties by index) quickly.

Topic: Heap scheduling (deadlines, leases). Min-heap of deadlines, lazy deletion, event simulation.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc