Merge overlapping intervals
Calendar views, availability pickers and text highlighters all end up with ranges that overlap and need collapsing before they can be drawn, or the same pixels get painted twice and the labels stack.
Implement mergeIntervals(intervals). intervals is an array of [start, end] number pairs, in no particular order, where start is never greater than end. Return a new array of [start, end] pairs covering exactly the same ground, with every overlap merged, sorted by start ascending. Intervals that merely touch — where one ends exactly where the next begins — count as overlapping and must be merged. An empty input returns an empty array. Do not modify the input array or the pairs inside it.
What it has to do
- Merge intervals that overlap, including ones that only touch at an endpoint.
- Return the result sorted by start value ascending.
- Accept input in any order.
- Return an empty array for an empty input.
- Do not mutate the input array or the pairs it contains.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.