array
intervals
]
Leetcode 0495. Teemo Attacking
https://leetcode.com/problems/teemo-attacking
If we look carefully at this problem we can see that all we need to do is to merge some intervals with equal length and return total length of merged intervals. Note also that intervals are already sorted by its beginings (and ends as well, because they have equal length), so usual sorting step can be skipped.
All we need to do is to traverse our timeSeries
and check if difference between current point and previous is more than duration
. If it is more, we add duration
to total sum, if it is less, we add difference between current and previous elements. Also we need to deal with border case of empty array and if array is not empty, add duration
in the end.
Complexity: time complexity is O(n)
, space complexity is O(1)
.
class Solution:
def findPoisonedDuration(self, timeSeries, duration):
n, out = len(timeSeries), 0
if n == 0: return 0
for i in range(n-1):
out += min(timeSeries[i+1] - timeSeries[i], duration)
return out + duration
If you like the solution, you can upvote it on leetcode discussion section: Problem 0495