Skip to content

Commit 4b22f12

Browse files
committed
Adding Efficient Solution for Problem 435 - Non-overlapping Intervals
1 parent 641c29b commit 4b22f12

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
##==================================
2+
## Leetcode
3+
## Student: Vandit Jyotindra Gajjar
4+
## Year: 2020
5+
## Problem: 435
6+
## Problem Name: Non-overlapping Intervals
7+
##===================================
8+
#
9+
#Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
10+
#
11+
#Example 1:
12+
#
13+
#Input: [[1,2],[2,3],[3,4],[1,3]]
14+
#Output: 1
15+
#Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
16+
#Example 2:
17+
#
18+
#Input: [[1,2],[1,2],[1,2]]
19+
#Output: 2
20+
#Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.
21+
#Example 3:
22+
#
23+
#Input: [[1,2],[2,3]]
24+
#Output: 0
25+
#Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
26+
27+
class Solution:
28+
def eraseOverlappingIntervals(self, intervals):
29+
if intervals == []: #Condition-check: If intervals is empty
30+
return 0 #We'll return 0 as no overlapping interval presenet
31+
intervals.sort(key = lambda x:x[1]) #Sort intervals list by 2nd element
32+
tmp = 0 #Initialize our tmp counter
33+
end = intervals[0][0] #Initialize end which will be first element of the first sublist
34+
for i in intervals: #Loop through intervals
35+
start = i[0] #Initialize start which will be first element in every sublist
36+
if start < end: #Condition-check: If start is less than end
37+
tmp += 1 #Then we'll increase out tmp counter as we encounter the overlapping list
38+
else: #Condition-check: Else
39+
end = i[1] #We'll update the end by 2nd element of ith sublist
40+
return tmp #We'll return tmp counter

0 commit comments

Comments
 (0)