Problem Description
Given a sorted integer array timeSeries where timeSeries[i] indicates the time Teemo attacks Ashe and an integer duration, calculate the total number of seconds that Ashe is poisoned. Each attack poisons Ashe for duration seconds, but if a new attack occurs before the previous poison effect ends, the poison timer is reset.
Key Insights
- The poison intervals can overlap when attacks occur before the previous poison duration is complete.
- For consecutive attacks, only a portion (min(duration, timeSeries[i+1] - timeSeries[i])) contributes additional poison time.
- The last attack always adds the full duration since there is no subsequent attack to overlap.
Space and Time Complexity
Time Complexity: O(n) where n is the number of attacks. Space Complexity: O(1)
Solution
The solution uses a simple iterative simulation:
- Initialize a total counter for poisoned time.
- Loop through the timeSeries array (except the last element) and for each attack, add the minimum of the fixed duration and the difference between the current and next attack time.
- After the loop, add the full duration for the last attack as there is no follow-up attack. This approach uses only constant extra space and runs in linear time relative to the number of attacks.