Skip to content
BytePatterns

Next Span to the Right

MediumTwo Heaps & K-Way Merge#two-heaps#max-heap~30m

Problem

A build system has a list of jobs, each a time span [start, end], and no two jobs share a start time. For every job, find the job that could run next on the same machine: the one with the smallest start that is at least this job's end. Return, for each job in input order, the index of that job, or -1 if there is none. A job whose start equals its own end may follow itself.

Examples

Input:  spans = [[3, 4], [2, 3], [1, 2]]
Output: [-1, 0, 1]
Why:    nothing starts at 4 or later; [3, 4] follows [2, 3], and [2, 3] follows [1, 2]
Input:  spans = [[1, 4], [2, 3], [3, 4]]
Output: [-1, 2, -1]
Input:  spans = [[1, 2]]
Output: [-1]
Why:    edge case, a single job has no successor

Hints

0 / 3

Stuck on the idea rather than the code? Two Heaps: Running Median covers it.