Skip to content

Commit 35700a5

Browse files
committed
added merge interval problem on the array ds
1 parent 2c15b8c commit 35700a5

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
from typing import List
2+
3+
4+
def merge_intervals(intervals: List[List[int]]) -> List[List[int]]:
5+
"""
6+
Merge all overlapping intervals.
7+
8+
Each interval is represented as a list of two integers [start, end].
9+
The function merges overlapping intervals and returns a list of
10+
non-overlapping intervals sorted by start time.
11+
12+
Parameters:
13+
intervals (List[List[int]]): A list of intervals.
14+
15+
Returns:
16+
List[List[int]]: A list of merged non-overlapping intervals.
17+
18+
Examples:
19+
>>> merge_intervals([[1, 3], [2, 6], [8, 10], [15, 18]])
20+
[[1, 6], [8, 10], [15, 18]]
21+
>>> merge_intervals([[1, 4], [4, 5]])
22+
[[1, 5]]
23+
>>> merge_intervals([[6, 8], [1, 3], [2, 4]])
24+
[[1, 4], [6, 8]]
25+
>>> merge_intervals([])
26+
[]
27+
>>> merge_intervals([[1, 4]])
28+
[[1, 4]]
29+
30+
Time Complexity:
31+
O(n log n), where n is the number of intervals (sorting step).
32+
33+
Space Complexity:
34+
O(n), for storing the merged intervals.
35+
"""
36+
37+
if not intervals:
38+
return []
39+
40+
# Sort intervals based on the start time
41+
intervals.sort(key=lambda interval: interval[0])
42+
43+
merged: List[List[int]] = [intervals[0]]
44+
45+
for current in intervals[1:]:
46+
last = merged[-1]
47+
48+
# If current interval overlaps with the last merged interval
49+
if current[0] <= last[1]:
50+
last[1] = max(last[1], current[1])
51+
else:
52+
merged.append(current)
53+
54+
return merged

0 commit comments

Comments
 (0)