Skip to content

Commit 90c224a

Browse files
authored
Upload: codedecks-in#56 Merge_Intervals (Python) (codedecks-in#4)
* 1513 * Upload: "Flower Planting with No adjacent"-Python * Upload: codedecks-in#56 Merge Intervals (Python)
1 parent ba9d2c9 commit 90c224a

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

Python/56_MergeIntervals.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#Difficluty - Medium
2+
#Speed = 33.94%
3+
'''
4+
First we will sort the intervals (with start time of the interval as the key), so that the (overlapping) intervals that could be merged comes adjacent. For Ex:
5+
Original Array -> [[0,2], [5,9], [1,3], [11,12]]
6+
Sorted Array -> [[0,2], [1,3], [5,9], [11,12]]
7+
Note => Time Complexity of Sorting is O(nlogn)
8+
Overlapping Condition: Two intervals (X and Y) are overlapping if end Time of first interval (X) is greater than start time of second interval (Y)
9+
that is,
10+
X.end > Y.start
11+
In case of [0,2] and [1,3], since 2 > 1, these intervals are overlapping.
12+
In case of [5,9] and [11,12], since 9 < 11, these intervals are *NOT* overlapping.
13+
So we will start with pushing the first interval in merged array.
14+
Then traverse the array, checking the overlapping condition of every interval with the last interval in merged array,
15+
1) If overlapping condition satisfy, We will update the end time of last interval in merged array as maximum of end time of both intervals.
16+
2) If overlapping condition doesnt satisy, We will push the interval in merged array
17+
'''
18+
#Time Complexity: O(nlogn)
19+
#Space Complexity: O(n)
20+
class Solution:
21+
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
22+
intervals.sort(key=lambda x: x[0]) #sort the intervals with starting time as the key
23+
merged = []
24+
for interval in intervals:
25+
if not merged or merged[-1][1] < interval[0]: #If merged list is empty (we need to push the first interval) or Overlapping condn doesnt satisfy
26+
merged.append(interval) #push the interval in merged array
27+
else: #else
28+
merged[-1][1] = max(merged[-1][1], interval[1]) #update the end time of last interval in merged array as maximum of end time of both intervals
29+
return merged

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@
6767
## Array
6868
| # | Title | Solution | Time | Space | Difficulty | Tag | Note|
6969
|-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----|
70+
56| [Merge Intervals](https://leetcode.com/problems/merge-intervals)|[Python](./Python/56_MergeIntervals.py)|33.94%|_O(nlogn)_|_O(n)_|Medium|Intervals||
7071

7172

7273
<br/>

0 commit comments

Comments
 (0)