1
1
'''
2
2
# 57. Insert Interval
3
3
4
- use binary search to find the index of the new interval.(bisect_left)
5
- insert the new interval into the list.
6
- iterate through the list and merge the intervals.
4
+ ## A. insert first, merge later
5
+ - use binary search to find the index of the new interval.(bisect_left)
6
+ - insert the new interval into the list.
7
+ - iterate through the list and merge the intervals.
7
8
8
- => insert first, merge later
9
-
10
- ## Time and Space Complexity
11
-
12
- ```
13
- TC: O(n)
14
- SC: O(n)
15
- ```
16
-
17
- #### TC is O(n):
18
- - do binary search to find correct index of the new interval. = O(log n)
19
- - inserting the new interval into the list. = O(n)
20
- - iterating through the list to merge the intervals. = O(n)
21
-
22
- #### SC is O(n):
23
- - using a list to store the intervals. = O(n)
9
+ ## B. insert, merge, insert
10
+ - inserting the intervals into the result list until finding the correct index of the new interval.
11
+ - merge the overlapping intervals than insert the newInterval into the result list.
12
+ - insert the remaining intervals into the result list.
24
13
'''
25
14
class Solution :
26
- def insert (self , intervals : List [List [int ]], newInterval : List [int ]) -> List [List [int ]]:
15
+ '''
16
+ # A. insert first, merge later
17
+ - TC: O(n)
18
+ - SC: O(n)
19
+ '''
20
+ def insertUsingBisectLeftToFindIndex (self , intervals : List [List [int ]], newInterval : List [int ]) -> List [List [int ]]:
27
21
start_idx = bisect_left ([interval [0 ] for interval in intervals ], newInterval [0 ]) # TC: O(log n)
28
22
29
23
intervals .insert (start_idx , newInterval ) # TC: O(n)
@@ -36,3 +30,31 @@ def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[Lis
36
30
result [- 1 ][1 ] = max (result [- 1 ][1 ], interval [1 ])
37
31
38
32
return result
33
+
34
+ '''
35
+ # B. insert, merge, insert
36
+ - TC: O(n)
37
+ - SC: O(n)
38
+ '''
39
+ def insert (self , intervals : List [List [int ]], newInterval : List [int ]) -> List [List [int ]]:
40
+ result = [] # SC: O(n)
41
+ i = 0
42
+ n = len (intervals )
43
+
44
+ # 1. insert until finding the correct index of newInterval
45
+ while i < n and intervals [i ][1 ] < newInterval [0 ]: # TC: O(n)
46
+ result .append (intervals [i ])
47
+ i += 1
48
+
49
+ # merge overapping intervals & insert newInterval
50
+ while i < n and intervals [i ][0 ] <= newInterval [1 ]: # TC: O(n)
51
+ newInterval [0 ] = min (newInterval [0 ], intervals [i ][0 ])
52
+ newInterval [1 ] = max (newInterval [1 ], intervals [i ][1 ])
53
+ i += 1
54
+ result .append (newInterval )
55
+
56
+ while i < n : # TC: O(n)
57
+ result .append (intervals [i ])
58
+ i += 1
59
+
60
+ return result
0 commit comments