forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJeehay28.ts
More file actions
31 lines (25 loc) · 738 Bytes
/
Jeehay28.ts
File metadata and controls
31 lines (25 loc) · 738 Bytes
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
// TC: O(n)
// SC: O(n)
function insert(intervals: number[][], newInterval: number[]): number[][] {
const result: number[][] = [];
const n = intervals.length;
let i = 0;
// Add all intervals that come before newInterval
while (i < n && intervals[i][1] < newInterval[0]) {
result.push(intervals[i]);
i++;
}
// Merge all overlapping intervals with newInterval
while (i < n && intervals[i][0] <= newInterval[1]) {
newInterval[0] = Math.min(intervals[i][0], newInterval[0]);
newInterval[1] = Math.max(intervals[i][1], newInterval[1]);
i++;
}
result.push(newInterval);
// Add remaining intervals after newInterval
while (i < n) {
result.push(intervals[i]);
i++;
}
return result;
}