Created
April 29, 2022 15:05
Cassidy Williams - question of the week 2021-04-25
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
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