Skip to content

Instantly share code, notes, and snippets.

@mkamranhamid
Created November 3, 2019 13:47
Show Gist options
  • Save mkamranhamid/ffba33a04b97930d9b453ad4c1d71469 to your computer and use it in GitHub Desktop.
Save mkamranhamid/ffba33a04b97930d9b453ad4c1d71469 to your computer and use it in GitHub Desktop.
this problem covers the basic understanding of how we can merge the two arrays if there values overlaps
// Input: [[1,3],[2,6],[8,10],[15,18]];
// Output: [[1,6],[8,10],[15,18]];
// Explaination: Since intervals [1,3] and [2, 6] overlaps, merge them into [1, 6].
var arr = [[1,3],[2,6],[8,10],[15,18]];
var newArr = [];
var index = 0;
while (index <= arr.length-1) {
var currentVal = arr[index];
var nextVal = arr[index+1] || 0;
if(nextVal[0] <= currentVal[1]){
newArr.push([currentVal[0], nextVal[1]]);
index += 2;
} else {
newArr.push(currentVal);
index += 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment