Created
August 1, 2020 18:52
-
-
Save jricaldi/4c29ca1d74845835532d3d1340d36e17 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// https://www.codewars.com/kata/52b7ed099cdc285c300001cd/train/javascript | |
function sumIntervals(intervals){ | |
intervals = intervals.sort(function(a, b) { // O(n) | |
return a[0] - b[0]; | |
}); | |
intervals = intervals.reduce(function(acc, el, index, array) { // O(n) | |
const anterior = array[index - 1]; | |
if (array.length > 1 && anterior !== undefined) { | |
if (el[0] < acc[acc.length - 1]) { | |
if (el[1] >= acc[acc.length - 1]) { | |
acc[acc.length - 1] = el[1]; | |
} | |
} else { | |
acc.push(...el); | |
} | |
} else { | |
acc.push(...el); | |
} | |
return acc; | |
}, []); | |
let result = 0; | |
for (let i = 0; i < intervals.length - 1 ; i+=2) { // O(2n) | |
result+=(intervals[i + 1] - intervals[i]); | |
} | |
return result; | |
} // O(n) + O(n) + O(2n) = 3O(n) = O(n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment