Resurfaced Road Stretches

EasyintervalsAlso known as Merge Intervals

Several crews resurfaced a country road this summer. Each logged its stretch as a pair of kilometre markers, like [3, 6] for kilometres 3 to 6. Crews often overlapped, and the log is in no particular order.

The county wants a clean map for drivers: the fewest stretches that show exactly which parts of the road are new.

Your task

Write mergeStretches(jobs). Each job is [start, end] with start ≤ end. Return the combined stretches as [start, end] pairs, sorted by start, with no two overlapping or touching.

Two jobs belong to the same stretch if they share any point, even just an endpoint: [2, 5] and [5, 9] become [2, 9]. An empty log returns an empty list.

mergeStretches(jobs: int[][]) → int[][]

Examples

Example 1
Input
jobs = [[8, 10], [1, 4], [3, 6]]
Output
[[1, 6], [8, 10]]
Why

Sorted by start: [1, 4], [3, 6], [8, 10]. The first two share kilometres 3 to 4, so together they cover 1 to 6. The job at 8 starts after 6, leaving a gap of old road.

Example 2
Input
jobs = [[2, 5], [5, 9], [12, 14]]
Output
[[2, 9], [12, 14]]
Why

One crew stopped at kilometre 5 and another started at 5, so there is no gap: 2 to 9 is one continuous new stretch.

Constraints

  • 0 ≤ jobs.length ≤ 10,000
  • 0 ≤ start ≤ end ≤ 1,000,000,000
Start with brute force

Scan all pairs of stretches; whenever two overlap, replace them with their union and start over. When no pair overlaps any more, sort the result.

Each scan checks O(n²) pairs, and you may need up to n scans: O(n³), around a trillion comparisons for 10,000 jobs. The waste is checking pairs that are far apart on the road.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code