Skip to content

Commit d13b5aa

Browse files
committed
D. J.:
- Added the leetcode problem and solution for 56 Merge Intervals
1 parent ce08764 commit d13b5aa

File tree

3 files changed

+37
-1
lines changed

3 files changed

+37
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
</h1>
2121
</div>
2222

23-
2423
This repository contains awesome LeetCode problems and solutions written in Python to prepare for coding interviews.
2524

2625
## Leetcode Problems & Solutions 💻
@@ -31,6 +30,7 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
3130
- [45 Jump Game II](https://leetcode.com/problems/jump-game-ii/description/)
3231
- [49 Group Anagrams](https://leetcode.com/problems/group-anagrams/description/)
3332
- [55 Jump Game](https://leetcode.com/problems/jump-game/description/)
33+
- [56 Merge Intervals](https://leetcode.com/problems/merge-intervals/description/)
3434
- [80 Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/)
3535
- [88 Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/description/)
3636
- [121 Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/)
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
6+
"""
7+
Given an array of intervals where intervals[i] = [starti, endi],
8+
merge all overlapping intervals, and return an array of the
9+
non-overlapping intervals that cover all the intervals in the input.
10+
"""
11+
intervals = sorted(intervals, key=lambda i: i[0])
12+
output = [intervals[0]]
13+
for start, end in intervals[1:]:
14+
last_end = output[-1][1]
15+
if start <= last_end:
16+
output[-1][1] = max(last_end, end)
17+
else:
18+
output.append([start, end])
19+
return output

tests/test_56_merge_intervals.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from typing import List
2+
3+
import pytest
4+
5+
from awesome_python_leetcode._56_merge_intervals import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["intervals", "expected"],
10+
argvalues=[
11+
([[1, 3], [2, 6], [8, 10], [15, 18]], [[1, 6], [8, 10], [15, 18]]),
12+
([[1, 4], [4, 5]], [[1, 5]]),
13+
],
14+
)
15+
def test_func(intervals: List[List[int]], expected: List[List[int]]):
16+
merged_intervals = Solution().merge(intervals)
17+
assert merged_intervals == expected

0 commit comments

Comments
 (0)