Count Integers in Intervals LeetCode solution in Python

1
class CountIntervals:
2

3
def __init__(self):
4
# initialize the merged intervals list as below to handle edge cases
5
self.interv = [(-inf, -inf), (inf, inf)]
6
self.cov = 0
7

8
def add(self, left: int, right: int) -> None:
9

10
interv = self.interv
11

12
# find the left most position for inserting of the new potentially merged interval
13
# we use `left - 1` because the interval coverage is inclusive
14
li = bisect.bisect_left(interv, left - 1, key=itemgetter(1))
15
lval = min(interv[li][0], left)
16

17
# find the right most position for inserting the new potentially merged interval
18
# we use `right + 1` because the interval coverage is inclusive
19
ri = bisect.bisect_right(interv, right + 1, key=itemgetter(0))
20
rval = max(interv[ri - 1][1], right)
21

22
# find the coverage of the intervals that will be replaced by the new interval
23
to_delete = 0
24
for _ in range(li, ri):
25
to_delete += interv[_][1] - interv[_][0] + 1
26

27
# udpate the coverage
28
self.cov += rval - lval + 1 - to_delete
29
interv[li:ri] = [(lval, rval)]
30

31
def count(self) -> int:
32
return self.cov

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0