LeetCode #56 Merge Intervals

Problem

Given a collection of intervals, merge all overlapping intervals.

Examples

1
2
3
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].
1
2
3
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.

Boundary Conditions

Solution

Method: Sort

Time Complexity: O(n log n)

Space Complexity: O(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e

class Solution:
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
if not intervals:
return []

left_pts = [interval.start for interval in intervals]
right_pts = [interval.end for interval in intervals]
ret = []
left_pts.sort()
right_pts.sort()

start_ptr = 0
end_ptr = 0
shift = 1

while start_ptr + shift < len(left_pts) and end_ptr < len(left_pts):
if left_pts[start_ptr + shift] <= right_pts[end_ptr]:
shift += 1
end_ptr += 1
else:
ret.append(Interval(left_pts[start_ptr], right_pts[end_ptr]))
end_ptr += 1
start_ptr = end_ptr
shift = 1

ret.append(Interval(left_pts[start_ptr], right_pts[end_ptr]))

return ret

or

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e

class Solution:
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
out = []

for i in sorted(intervals, key=lambda i: i.start):
if out and i.start <= out[-1].end:
out[-1].end = max(out[-1].end, i.end)
else:
out.append(i)

return out