Skip to content

Commit 2dedc10

Browse files
Add 'Non-overlapping Intervals'
1 parent 420d06b commit 2dedc10

File tree

3 files changed

+53
-0
lines changed

3 files changed

+53
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,8 @@ A collection of LeetCode solutions
8080

8181
[Next Permutation](./src/next_permutation.py)
8282

83+
[Non Overlapping Intervals](./src/non_overlapping_intervals.py)
84+
8385
[Number of Visible People in a Queue](./src/number_of_visible_people_in_a_queue.py)
8486

8587
[Palindromic Substrings](./src/palindromic_substrings.py)

src/non_overlapping_intervals.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""
2+
435. Non-overlapping Intervals
3+
4+
https://leetcode.com/problems/non-overlapping-intervals
5+
6+
NOTES
7+
* A common routine for interval problems is to sort the array of intervals
8+
by each interval's starting index.
9+
10+
We start by sorting the interval array by starting index (O(nlog n)). Since the
11+
starting index is now monotonically increasing, we remove overlapping intervals
12+
while taking the lower ending index until there is no overlap.
13+
"""
14+
15+
import sys
16+
17+
18+
class Solution:
19+
def eraseOverlapIntervals(self, intervals: list[list[int]]) -> int:
20+
intervals.sort(key=lambda x: x[0])
21+
count, lo = 0, -sys.maxsize
22+
for interval in intervals:
23+
if interval[0] < lo:
24+
count += 1
25+
lo = min(lo, interval[1])
26+
else:
27+
lo = interval[1]
28+
return count
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
"""
2+
435. Non-overlapping Intervals
3+
4+
https://leetcode.com/problems/non-overlapping-intervals
5+
"""
6+
7+
from unittest import TestCase
8+
9+
from src.non_overlapping_intervals import Solution
10+
11+
12+
class TestSolution(TestCase):
13+
def test_1(self):
14+
exp = 1
15+
assert Solution().eraseOverlapIntervals([[1, 2], [2, 3], [3, 4], [1, 3]]) == exp
16+
17+
def test_2(self):
18+
exp = 2
19+
assert Solution().eraseOverlapIntervals([[1, 2], [1, 2], [1, 2]]) == exp
20+
21+
def test_3(self):
22+
exp = 0
23+
assert Solution().eraseOverlapIntervals([[1, 2], [2, 3]]) == exp

0 commit comments

Comments
 (0)