Skip to content

Commit 0aa872d

Browse files
committed
update solution: insert-interval
1 parent b906f60 commit 0aa872d

File tree

1 file changed

+42
-20
lines changed

1 file changed

+42
-20
lines changed

insert-interval/dusunax.py

Lines changed: 42 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,23 @@
11
'''
22
# 57. Insert Interval
33
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.
78
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.
2413
'''
2514
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]]:
2721
start_idx = bisect_left([interval[0] for interval in intervals], newInterval[0]) # TC: O(log n)
2822

2923
intervals.insert(start_idx, newInterval) # TC: O(n)
@@ -36,3 +30,31 @@ def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[Lis
3630
result[-1][1] = max(result[-1][1], interval[1])
3731

3832
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

Comments
 (0)