56. Merge Intervals
[Medium] “Given a collection of intervals, merge all overlapping intervals."
Python3:
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if len(intervals) <= 1:
return intervals
else:
res = []
sorted_intervals = sorted(intervals)
last_low = sorted_intervals[0][0]
last_high = sorted_intervals[0][1]
for i in range(1, len(sorted_intervals)):
current = sorted_intervals[i]
if current[0] <= last_high:
# merge, taking larger window
last_high = max(last_high, current[1])
else:
# add last to res and track next interval
res.append([last_low, last_high])
last_low = current[0]
last_high = current[1]
# encapsulate last interval
if i == (len(sorted_intervals) - 1):
res.append([last_low, last_high])
return res