Scriptdrill

Level 4: Data shaping Exercise 55 of 76 Free

Merge overlapping intervals

A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.

The task

Each interval is a pair `[start, end]` with `start <= end`. Return a new array where every pair of intervals that overlap or touch has been merged (`[1, 3]` and `[3, 5]` become `[1, 5]`), sorted by start. The input is not sorted and must not be changed. Numbers can be negative and an interval can be a single point like `[2, 2]`.

What this exercise teaches

After sorting by start, an interval can only overlap the most recent merged one, so one pass is enough. Math.max matters when an interval is fully inside the previous one ([1, 10] then [2, 3]); copying first matters because sort works in place.

A hint if you get stuck

Sort a copy by start, then walk it keeping the last merged interval: if the next start is `<=` the last end, extend the last end with `Math.max`; otherwise push a new interval.

Try it now, free, no account needed

Every exercise on Scriptdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.

Open this exercise

More exercises in Data shaping