-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinsert-interval.py
More file actions
32 lines (21 loc) · 812 Bytes
/
insert-interval.py
File metadata and controls
32 lines (21 loc) · 812 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
31
32
# Leetcode 57. Insert Interval
#
# Link: https://leetcode.com/problems/insert-interval/
# Difficulty: Medium
# Solution using DP.
# Complexity:
# O(N) time | where N represent the number of intervals
# O(1) space
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
result = []
for i in range(len(intervals)):
if newInterval[1] < intervals[i][0]:
result.append(newInterval)
return result + intervals[i:]
elif newInterval[0] > intervals[i][1]:
result.append(intervals[i])
else:
newInterval = [min(newInterval[0], intervals[i][0]), max(newInterval[1], intervals[i][1])]
result.append(newInterval)
return result