File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change 1+ # Time Complexity: O(N) - iterate through the intervals once.
2+ # Space Complexity: O(N) - store the merged intervals in a new list.
3+
4+ class Solution :
5+ def insert (self , intervals : List [List [int ]], newInterval : List [int ]) -> List [List [int ]]:
6+ output = []
7+ start , end = newInterval
8+
9+ for interval in intervals :
10+ if interval [1 ] < start :
11+ # no overlap, and the current interval ends before newInterval starts
12+ output .append (interval )
13+ elif interval [0 ] > end :
14+ # no overlap, and the current interval starts after newInterval ends
15+ output .append ([start , end ]) # insert merged interval before appending the remaining ones
16+ output .extend (intervals [intervals .index (interval ):]) # append remaining intervals
17+ return output
18+ else :
19+ # overlapping case: merge intervals
20+ start = min (start , interval [0 ])
21+ end = max (end , interval [1 ])
22+
23+ # add the merged interval at the end if it wasn't added earlier
24+ output .append ([start , end ])
25+
26+ return output
You can’t perform that action at this time.
0 commit comments