File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 1+ # 56. Merge Intervals
2+
3+ ## Solution
4+ - Runtime: O(Nlog(N))
5+ - Space: O(1) (Assuming result isn't considered extra space)
6+ - N = Number of elements in intervals
7+
8+ By sorting the intervals, we can then recreate the result by comparing previous intervals with the current interval from left to right.
9+ In this way, we can check if the two intervals overlap each other after the sort.
10+
11+ ```
12+ class Solution:
13+ def merge(self, intervals: List[List[int]]) -> List[List[int]]:
14+ if len(intervals) == 0:
15+ return []
16+ intervals.sort(key=lambda x: x[0])
17+ result = list()
18+ new_interval = intervals[0]
19+ for interval in intervals[1:]:
20+ if interval[0] <= new_interval[1]: # do they overlap?
21+ new_interval[1] = max(interval[1], new_interval[1])
22+ else:
23+ result.append(new_interval)
24+ new_interval = interval
25+ result.append(new_interval)
26+ return result
27+ ```
28+
29+ ## Brownie Points
30+ You can do some more optimizations for some inputs if you mention binary search.
31+ Since after the sort, we can binary search to find the index of the furthest right interval that is overlapping or itself.
You can’t perform that action at this time.
0 commit comments