Skip to content

Instantly share code, notes, and snippets.

@g-bel
Created April 29, 2022 15:05
Show Gist options
  • Save g-bel/7f7680a30979ad3530acc3bed1ac4693 to your computer and use it in GitHub Desktop.
Save g-bel/7f7680a30979ad3530acc3bed1ac4693 to your computer and use it in GitHub Desktop.
Cassidy Williams - question of the week 2021-04-25
const mergeIntervals = (arr) => {
let result = [arr[0]];
let resultIndex = 0;
for (let i = 1; i < arr.length; i++) {
if (result[resultIndex][1] < arr[i][0]) {
resultIndex++;
result.push(arr[i]);
} else {
if (result[resultIndex][1] < arr[i][1]) {
result[resultIndex][1] = arr[i][1];
}
}
}
return result;
};
let result = JSON.stringify(mergeIntervals([[1, 6], [8, 10], [15, 20]]));
console.assert(result === '[[1,6],[8,10],[15,20]]', `Expected: '[[1,6],[8,10],[15,20]]' | Returned: '${result}'`);
console.log(result);
result = JSON.stringify(mergeIntervals([[1, 2], [2, 7]]));
console.assert(result === '[[1,7]]', `Expected: '[[1,7]]' | Returned: '${result}'`);
console.log(result);
result = JSON.stringify(mergeIntervals([[2, 5], [3, 4], [7, 11], [8, 9], [10, 12]]));
console.assert(result === '[[2,5],[7,12]]', `Expected: '[[2,5],[7,12]]' | Returned: '${result}'`);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment