Leet Code 56. Merge Intervals — Explained Python3 Solution

Image for post

Problem Description

Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.

Solution

Obvious Solution

Best Solution (to me)



Image for post

class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
'''
Detailed graphical explanation:
https://medium.com/@edward.zhou/leet-code-56-merge-intervals-explained-python3-solution-89b3297e81a1
I can compare each one of intervals against the other, it will be
a n to n comparison and make the complexity O(n^2).
If intervals are ordered by start times (complexity is O(nlogn)),
then I just need to compare the two contious internals which is a
O(n) work. Total complexity will be O(nlogn + n) = O(nlogn)
'''
intervals = sorted(intervals, key=lambda x:x[0])
ret = []
for i in intervals:
newInterval = i
#compare with the last one in ret
if ret:
if ret[-1][1] >= i[0]:
#merge and then replace the last one in ret
newInterval = ret.pop()
if i[1] > newInterval[1]:
newInterval[1] = i[1]
ret.append(newInterval)
return ret
view raw lc56.py hosted with ❤ by GitHub

Time & Space Complexity

Python 3 knowledge points

Extended Reading

Comments

Popular posts from this blog

Leet Code 84. Largest Rectangle in Histogram — Graphically Explained Python3 Solution

Leet Code 1060. Missing Element in Sorted Array — Explained Python3 Solution

LeetCode 23. Merge k Sorted Lists— Graphically Explained Python3 Solution