Skip to content

Commit b21dd7e

Browse files
committed
Sync LeetCode submission Runtime - 3 ms (93.57%), Memory - 20.8 MB (27.05%)
1 parent c760ab5 commit b21dd7e

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

0056-merge-intervals/README.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<p>Given an array&nbsp;of <code>intervals</code>&nbsp;where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, merge all overlapping intervals, and return <em>an array of the non-overlapping intervals that cover all the intervals in the input</em>.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
6+
<pre>
7+
<strong>Input:</strong> intervals = [[1,3],[2,6],[8,10],[15,18]]
8+
<strong>Output:</strong> [[1,6],[8,10],[15,18]]
9+
<strong>Explanation:</strong> Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
10+
</pre>
11+
12+
<p><strong class="example">Example 2:</strong></p>
13+
14+
<pre>
15+
<strong>Input:</strong> intervals = [[1,4],[4,5]]
16+
<strong>Output:</strong> [[1,5]]
17+
<strong>Explanation:</strong> Intervals [1,4] and [4,5] are considered overlapping.
18+
</pre>
19+
20+
<p>&nbsp;</p>
21+
<p><strong>Constraints:</strong></p>
22+
23+
<ul>
24+
<li><code>1 &lt;= intervals.length &lt;= 10<sup>4</sup></code></li>
25+
<li><code>intervals[i].length == 2</code></li>
26+
<li><code>0 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>4</sup></code></li>
27+
</ul>

0056-merge-intervals/solution.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Approach 2: Sorting
2+
3+
# Time: O(n log n)
4+
# Space: O(n)
5+
6+
class Solution:
7+
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
8+
intervals.sort(key=lambda x: x[0])
9+
10+
merged = []
11+
for interval in intervals:
12+
# if the list of merged intervals is empty or if the current
13+
# interval does not overlap with the previous, simply append it.
14+
if not merged or merged[-1][1] < interval[0]:
15+
merged.append(interval)
16+
17+
else:
18+
merged[-1][1] = max(merged[-1][1], interval[1])
19+
20+
return merged
21+

0 commit comments

Comments
 (0)