-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertInterval.py
More file actions
24 lines (20 loc) · 814 Bytes
/
Copy pathinsertInterval.py
File metadata and controls
24 lines (20 loc) · 814 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
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
result = []
i = 0
n = len(intervals)
# Add all intervals BEFORE newInterval starts
while i < n and newInterval[0] > intervals[i][-1]:
result.append(intervals[i])
i += 1
# Merge all overlapping intervals with newInterval
while i < n and newInterval[-1] >= intervals[i][0]:
newInterval[0] = min(intervals[i][0], newInterval[0])
newInterval[1] = max(intervals[i][-1], newInterval[-1])
i += 1
result.append(newInterval)
# Add all intervals AFTER newInterval ends
while i < n:
result.append(intervals[i])
i += 1
return result