Created
November 1, 2024 08:27
-
-
Save sAVItar02/b21ad25b01189332ddd012f888005c14 to your computer and use it in GitHub Desktop.
Merge Intervals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[][]} intervals | |
* @return {number[][]} | |
*/ | |
var merge = function(intervals) { | |
let temp = []; | |
intervals.sort((a, b) => a[0] - b[0]) | |
for(let i=0; i<intervals.length - 1; i++) { | |
if(intervals[i][1] >= intervals[i+1][0]) { | |
temp = intervals.splice(i+1, 1); | |
if(intervals[i][1] <= temp[0][1]) { | |
intervals[i][1] = temp[0][1]; | |
} | |
if(intervals[i][0] >= temp[0][0]) { | |
intervals[i][0] = temp[0][0] | |
} | |
i--; | |
} | |
} | |
return intervals; | |
}; | |
// Sort the array (nlog(n)) | |
// run a loop from the start to n-1 | |
// if the current element last value is greater then the second element first value, then remove the second element and store it in temp | |
// if current interval last element is lesser then the current interval last element becomes temp variable first element | |
// do the same for the first element | |
// time - O(nlog(n)) | |
// space - O(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment