Created
May 7, 2015 15:46
-
-
Save acusti/5307437d551f86d2f3b7 to your computer and use it in GitHub Desktop.
A JS (ES6) function for this problem: https://www.interviewcake.com/question/merging-ranges
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
// Take an array of meeting time ranges and return an array of condensed ranges | |
// https://www.interviewcake.com/question/merging-ranges | |
function condense_meeting_times(times) { | |
let timeline = []; | |
times.forEach((time) => { | |
//time[0], time[1] | |
// time is a tuple witih beginning and end | |
if (timeline[time[0]] === undefined) { | |
timeline[time[0]] = time[1]; | |
return; | |
} | |
// If start already exists, update its value if current end is greater | |
if (timeline[time[0]] < time[1]) { | |
timeline[time[0]] = time[1]; | |
} | |
}); | |
let condensed_times = []; | |
let time = []; | |
timeline.forEach((end, start) => { | |
// start is starting time, end is ending time | |
// Initialize time period tracking | |
if (!time.length) { | |
time = [start, end]; | |
return; | |
} | |
// If start is greater than time[1] | |
if (start > time[1]) { | |
// Append previous time period | |
condensed_times.push(time); | |
// Start a new time period | |
time = [start, end]; | |
return; | |
} | |
// If start is less than time[1] | |
if (end > time[1]) { | |
time[1] = end; | |
} | |
}); | |
// Append the last time period | |
condensed_times.push(time); | |
return condensed_times; | |
} | |
// Given | |
// [[0, 1], [3, 5], [4, 8], [10, 12], [9, 10]] | |
// Expect | |
// [[0, 1], [3, 8], [9, 12]] | |
export default condense_meeting_times; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment