Teemo Attacking Problem
Description
LeetCode Problem 495.
Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly duration seconds. More formally, an attack at second t will mean Ashe is poisoned during the inclusive time interval [t, t + duration - 1]. If Teemo attacks again before the poison effect ends, the timer for it is reset, and the poison effect will end duration seconds after the new attack.
You are given a non-decreasing integer array timeSeries, where timeSeries[i] denotes that Teemo attacks Ashe at second timeSeries[i], and an integer duration.
Return the total number of seconds that Ashe is poisoned.
Example 1:
Input: timeSeries = [1,4], duration = 2
Output: 4
Explanation: Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.
Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.
Example 2:
Input: timeSeries = [1,2], duration = 2
Output: 3
Explanation: Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.
Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.
Constraints:
- 1 <= timeSeries.length <= 10^4
- 0 <= timeSeries[i], duration <= 10^7
- timeSeries is sorted in non-decreasing order.
Solution
Approach: Add Up the Gaps
Each attack poisons Ashe from its own second until either duration seconds have passed or the next attack resets the timer, whichever comes first. So attack i adds exactly min(timeSeries[i+1] - timeSeries[i], duration) new poisoned seconds before the next attack takes over:
- If the gap is at least
duration, the poison runs out on its own and contributes alldurationseconds. - If the gap is shorter, the next attack resets the timer and only the gap counts. The seconds after that belong to the next attack, so nothing is counted twice.
The last attack has no next attack, so it always contributes the full duration. Add it once at the end.
For timeSeries = [1,2] and duration = 2: the first attack contributes min(1, 2) = 1 second, the last one 2 seconds, for a total of 3.
The array is already sorted, so a single pass is enough. No need to mark seconds one by one, which would be far too slow with times up to 107.
Complexity: O(n) time and O(1) space, where n is the length of timeSeries.
class Solution:
def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:
total = 0
for i in range(len(timeSeries) - 1):
# The poison from attack i lasts until the next attack resets it, or for the full duration.
total += min(timeSeries[i + 1] - timeSeries[i], duration)
return total + duration # the last attack always runs its full duration