Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Merge Intervals

Sortingmedium

Course · Section 11: Working With Arrays · Lecture 172: Sorting Arrays

Given `intervals` as an array of `[start, end]` pairs, implement `merge(intervals)` returning the non-overlapping intervals after merging overlaps, sorted by start.

Sample tests

Input: merge([[1,3],[2,6],[8,10],[15,18]])
Output: [[1,6],[8,10],[15,18]]
Input: merge([[1,4],[4,5]])
Output: [[1,5]]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Comparing against the wrong end when deciding to merge.

Learning resources

  • MDN: Array.prototype.sort
Approach & explanation (try first)

Sorting by start then merging overlapping ends gives the result in O(n log n) time.

Loading...
⌘/Ctrl + Enter

Run your code to see results.