I'm attempting to solve the merge overlapping intervals problem and have the working solution below. However there's a piece of logic that im having problems understanding. Namely the part where the currentInterval[1] gets updated with the max between currentInterval[1] and nextInterval[1]. This piece of code also updates the last array in the mergedIntervals array and I don't fully understand how this is happening as i dont see how the currentInterval is linked with the last array in mergedIntervals. Could someone please explain how mergedIntervals is being updated when we set currentInterval[1]?
const array = [
[1, 2],
[4, 7],
[9, 10],
[3, 5],
[6, 8],
];
function mergeOverlappingIntervals(array) {
let sortedIntervals = array.sort(function (a, b) {
return a[0] - b[0];
});
let mergedIntervals = [];
let currentInterval = sortedIntervals[0];
mergedIntervals.push(currentInterval);
for (let nextInterval of sortedIntervals) {
if (currentInterval[1] >= nextInterval[0]) {
currentInterval[1] = Math.max(
currentInterval[1],
nextInterval[1],
);
} else {
currentInterval = nextInterval;
mergedIntervals.push(nextInterval);
}
}
return mergedIntervals;
}
const result = mergeOverlappingIntervals(array);
console.log('result', result);