Skip to content

Commit f481e50

Browse files
committed
Solution added.
1 parent 2268011 commit f481e50

File tree

1 file changed

+54
-0
lines changed
  • 30 Days of October Challange/Week 1/4. Remove Covered Intervals

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
"""
2+
Given a list of intervals, remove all intervals that are covered by another interval in the list.
3+
4+
Interval [a,b) is covered by interval [c,d) if and only if c <= a and b <= d.
5+
6+
After doing so, return the number of remaining intervals.
7+
8+
9+
10+
Example 1:
11+
12+
Input: intervals = [[1,4],[3,6],[2,8]]
13+
Output: 2
14+
Explanation: Interval [3,6] is covered by [2,8], therefore it is removed.
15+
Example 2:
16+
17+
Input: intervals = [[1,4],[2,3]]
18+
Output: 1
19+
Example 3:
20+
21+
Input: intervals = [[0,10],[5,12]]
22+
Output: 2
23+
Example 4:
24+
25+
Input: intervals = [[3,10],[4,10],[5,11]]
26+
Output: 2
27+
Example 5:
28+
29+
Input: intervals = [[1,2],[1,4],[3,4]]
30+
Output: 1
31+
32+
33+
Constraints:
34+
35+
1 <= intervals.length <= 1000
36+
intervals[i].length == 2
37+
0 <= intervals[i][0] < intervals[i][1] <= 10^5
38+
All the intervals are unique.
39+
"""
40+
41+
42+
class Solution:
43+
def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
44+
intervals.sort(key=lambda a: a[0])
45+
result = [intervals[0]]
46+
for interval in intervals[1:]:
47+
if interval[0] >= result[-1][0] and interval[1] <= result[-1][1]:
48+
continue
49+
elif interval[0] == result[-1][0] and interval[1] > result[-1][1]:
50+
result.pop()
51+
result.append(interval)
52+
else:
53+
result.append(interval)
54+
return len(result)

0 commit comments

Comments
 (0)