File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ '''
2
+ # 57. Insert Interval
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.
7
+
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)
24
+ '''
25
+ class Solution :
26
+ def insert (self , intervals : List [List [int ]], newInterval : List [int ]) -> List [List [int ]]:
27
+ start_idx = bisect_left ([interval [0 ] for interval in intervals ], newInterval [0 ]) # TC: O(log n)
28
+
29
+ intervals .insert (start_idx , newInterval ) # TC: O(n)
30
+
31
+ result = [] # SC: O(n)
32
+ for interval in intervals : # TC: O(n)
33
+ if not result or result [- 1 ][1 ] < interval [0 ]:
34
+ result .append (interval )
35
+ else :
36
+ result [- 1 ][1 ] = max (result [- 1 ][1 ], interval [1 ])
37
+
38
+ return result
You can’t perform that action at this time.
0 commit comments