|
| 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 |
0 commit comments