Merge Intervals Solution In JavaScript

Sorting

In the example above the intervals happen to be sorted by the first value of each interval. This might not necessarily be the case with other inputs so first we have to sort the original input array. We can do this using JavaScripts built in sort method which will run in O(n log n) time.

Results Array

Next we want to create a new array that we will add the merged intervals to. To begin with, we want to add the first interval from the original array of intervals.

For Loop With Conditionals

Next we use a for loop to iterate through the sorted array. We start the for loop at the second interval (index 1) because we have already adding the first interval. From there we use an “if else” conditional to check if the beginning value of the current interval is less than or equal to the end value of the last interval that was added to the results array.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store