forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0057-insert-interval.js
46 lines (37 loc) · 1.31 KB
/
0057-insert-interval.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* https://leetcode.com/problems/insert-interval/
* Time O(N) | Space O(N)
* @param {number[][]} intervals
* @param {number[]} newInterval
* @return {number[][]}
*/
var insert = function (intervals, newInterval) {
const { beforeIndex, before } = getBefore(intervals, newInterval);
const afterIndex = mergeIntervals(intervals, newInterval, beforeIndex);
const after = intervals.slice(afterIndex);
return [...before, newInterval, ...after];
};
const getBefore = (intervals, newInterval, index = 0, before = []) => {
const hasGap = ([prevStart, prevEnd], [currStart, currEnd]) =>
prevEnd < currStart;
while (index < intervals.length && hasGap(intervals[index], newInterval)) {
const current = intervals[index];
before.push(current);
index++;
}
return { beforeIndex: index, before };
};
const mergeIntervals = (intervals, newInterval, index) => {
const hasOverlap = ([prevStart, prevEnd], [currStart, currEnd]) =>
currStart <= prevEnd;
while (
index < intervals.length &&
hasOverlap(newInterval, intervals[index])
) {
const current = intervals[index];
newInterval[0] = Math.min(newInterval[0], current[0]);
newInterval[1] = Math.max(newInterval[1], current[1]);
index++;
}
return index;
};