Resurfaced Road Stretches

EasyintervalsAlso known as Merge Intervals

A county resurfaced a long country road this summer. Several crews worked on it, and each crew logged the stretch it covered 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 a list of [start, end] pairs, sorted by start, where no two stretches overlap or touch.

Two jobs belong to the same stretch if they share any point, including 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 the jobs are [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, so there is a gap of old road between them.

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

Keep scanning all pairs of stretches; whenever two overlap, replace them with their union, and start over. Stop when no pair overlaps, then sort.

Each scan checks O(n²) pairs, and you may need up to n scans, so it is O(n³) in the worst case. With 10,000 jobs that is around a trillion comparisons. 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