Skip to content

Commit cda10d5

Browse files
committed
solve: nonOverlappingIntervals
1 parent b1392fc commit cda10d5

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Time Complexity: O(N log N)
2+
# (1) sorting the intervals takes O(N log N), and
3+
# (2) iterating through them takes O(N).
4+
# (3) so the overall complexity is O(N log N).
5+
# Space Complexity: O(1) - only use a few extra variables (end and res), so the space usage is constant.
6+
7+
class Solution:
8+
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
9+
# sort intervals by their ending time
10+
intervals.sort(key=lambda x: x[1])
11+
12+
# track the last non-overlapping interval's end
13+
end = float('-inf')
14+
# count the number of intervals we need to remove
15+
res = 0
16+
17+
for interval in intervals:
18+
# if it overlaps with the last interval
19+
if interval[0] < end:
20+
# need to remove this one
21+
res += 1
22+
else:
23+
# otherwise, update the end to the current interval's end
24+
end = interval[1]
25+
return res

0 commit comments

Comments
 (0)