Skip to content

Instantly share code, notes, and snippets.

@danielyaa5
Last active February 25, 2020 21:23
Show Gist options
  • Save danielyaa5/195e921eaea53aa2a584b8133097009e to your computer and use it in GitHub Desktop.
Save danielyaa5/195e921eaea53aa2a584b8133097009e to your computer and use it in GitHub Desktop.
/* System Uptime monitor:
A system is made of multiple different components. When one goes down, the entire system is down.
Given intervals of component downtimes, return the intervals during which the system was operational.
Hours are marked in military time 0-23.
input: []
Output: [[0,23]]
input: [
[0, 1]
]
Output: [[1,23]]
input: [
[0, 1],
[10,11]
]
Output: [[1,10],[11,23]]
input: [
[9,10], [13,14],
[7, 9], [11,12], [17,18],
]
Output system uptimes:
[[0,7], [10,11], [12, 13], [14,17], [18,23]]
input: [[0. 5], [2, 3]]
merged input: [[2, 5], [7, 10]]
[0, 2], [5, 7], [10, 23]
output: [5, 23]
*/
const solution = (intervals) => {
intervals.sort(([a, b], [c, d]) => a - c);
const mergedIntervals = [];
for (let i = 0; i < intervals.length; i++) {
const interval = intervals[i];
if (i === 0) {
mergedIntervals.push(interval);
continue;
}
const [start, end] = interval;
const mergedHead = mergedIntervals[mergedIntervals.length - 1];
const [mergedHeadStart, mergedHeadEnd] = mergedHead;
if (mergedHeadEnd >= start) {
mergedHead[1] = Math.max(mergedHeadEnd, end);
} else {
mergedIntervals.push(interval);
}
}
const result = [];
let lastEnd = 0;
for (let i = 0; i < mergedIntervals.length; i++) {
const mergedInterval = mergedIntervals[i];
const [start, end] = mergedInterval;
if (start === 0) {
lastEnd = end;
continue;
}
result.push([lastEnd, start]);
lastEnd = end;
}
if (lastEnd < 23) result.push([lastEnd, 23]);
return result;
}
const betterSolution = (intervals) => {
intervals.sort(([a, b], [c, d]) => a - c);
const result = [];
let lastEnd = 0;
for (let i = 0; i < intervals.length; i++) {
const [start, end] = intervals[i];
if (lastEnd >= start || start === 0) {
lastEnd = Math.max(lastEnd, end);
} else {
result.push([lastEnd, start])
lastEnd = end;
}
}
if (lastEnd < 23) result.push([lastEnd, 23]);
return result;
}
const test1 = [
[9,10], [13,14],
[7, 9], [11,12], [17,18],
]
const test2 = [[0, 5], [2, 3], [3, 7]]
const test3 = [];
const test4 = [[0, 1]];
console.log(betterSolution(test1))
console.log(betterSolution(test2))
console.log(betterSolution(test3))
console.log(betterSolution(test4))
// how would you design this to check for percentages of uptime in a month and day with minute time interval resolution
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment