File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed
non-overlapping-intervals Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments