Merge Overlapping Intervals

A corgi smiling happily

Write a function that takes in a non-empty array of arbitrary intervals, merges any overlapping intervals, and returns the new intervals in no particular order.

Each interval is an array of two integers, with interval[0] as the start of the interval and interval[1] as the end of the interval.

Note that back-to-back intervals aren’t considered to be overlapping. For example, [1, 5] and [6, 7] aren’t overlapping; however, [1, 6] and [6, 7] are indeed overlapping.

Also note that the start of any particular interval will always be less than or equal to the end of that interval.

Sample Input

1intervals = [[1, 2], [3, 5], [4, 7], [6, 8], [9, 10]]

Sample Output

1[[1, 2], [3, 8], [9, 10]]
2// Merge the intervals [3, 5], [4, 7], and [6, 8].
3// The intervals could be ordered differently.

Hints

Hint 1

The problem asks you to merge overlapping intervals. How can you determine if two intervals are overlapping?

Hint 2

Sort the intervals with respect to their starting values. This will allow you to merge all overlapping intervals in a single traversal through the sorted intervals

Hint 3

After sorting the intervals with respect to their starting values, traverse them, and at each iteration, compare the start of the next interval to the end of the current interval to look for an overlap. If you find an overlap, mutate the current interval so as to merge the next interval into it.

Optimal Space & Time Complexity

O(nlog(n)) time | O(n) space - where n is the length of the input array

Solution-1
1function mergeOverlappingIntervals(array) {
2 let arr = []
3 let arrLen = array.length
4
5 array.sort((a, b) => a[0] - b[0])
6
7 let i = 0
8 let j = 1
9
10 while (i < arrLen) {
11 let iStart = array[i][0]
12 let iEnd = array[i][1]
13
14 if (i + 1 == arrLen) {
15 arr.push([iStart, iEnd])
16 break;
17 }
18
19 while (j < arrLen && array[j][0] <= iEnd) {
20 iEnd = Math.max(array[j][1], iEnd)
21 j++
22 }
23 arr.push([iStart, iEnd])
24 i = j
25 j++
26}
27
28 return arr;
29}
Solution-2
1function mergeOverlappingIntervals(array) {
2 array.sort((a, b) => a[0] - b[0])
3
4 const arr = []
5 let current = array[0]
6 arr.push(current)
7
8 for (const next of array) {
9 const [start, end] = current
10 const [nextStart, nextEnd] = next
11
12 if (end >= nextStart) {
13 current[1] = Math.max(end, nextEnd)
14 } else {
15 current = next
16 arr.push(current)
17 }
18 }
19
20 return arr;
21}

🥷

Do you have any questions, or simply wish to contact me privately? Don't hesitate to shoot me a DM on Twitter.

Have a wonderful day.
Abhishek 🙏

Subscribe to my newsletter

Get email from me about my ideas, full-stack development resources, tricks and tips as well as exclusive previews of upcoming articles.

No spam. Just the highest quality ideas you’ll find on the web.