A player hits an enemy with a poison spell. A hit at second t keeps the enemy poisoned for duration seconds: seconds t through t + duration − 1, both included.
If a new hit lands while the enemy is still poisoned, the poison does not stack. The timer restarts, and the poison now ends duration seconds after the new hit.
You are given timeSeries, the seconds at which hits land, sorted from earliest to latest, and the number duration. Return how many seconds in total the enemy spends poisoned.
Example 1
Input: timeSeries = [1, 3, 8, 9], duration = 3 Output: 9 Why: seconds 1 to 5 and 8 to 11 are poisoned
2 more examples and the constraints
Example 2
Input: timeSeries = [2, 6], duration = 4 Output: 8 Why: 2 to 5, then 6 to 9: they touch but never overlap
Example 3
Input: timeSeries = [5, 5, 5], duration = 2 Output: 2 Why: three hits at the same second poison only 5 and 6
Constraints
- 1 ≤ length of timeSeries ≤ 10,000
- 0 ≤ timeSeries[i] ≤ 10,000,000 and 0 ≤ duration ≤ 10,000,000
- timeSeries is sorted in non-decreasing order (equal times are allowed)
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Mark every secondO(n·d)
- Count each gapO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 hits with a long duration | Verdict |
|---|---|---|---|
| Mark every second | O(n·d) | Correct, but the set explodes | |
| Count each gap | O(n) | Best; one pass, no memory |
n = number of hits, d = duration.
Edge cases to test
- Duration 0. No second is ever poisoned, so the answer is 0 for any list.
- Hits at the same second. [5, 5, 5] gives gaps of 0, which add nothing; only the last hit counts.
- Ranges that just touch. A gap equal to the duration means no overlap: both hits get their full time.
- One hit. The loop does not run; the answer is just the duration.
Common mistakes
- Adding the full duration for every hit, which counts overlapping seconds twice.
- Forgetting the last hit, which always adds the full duration.
- Using t + duration as an included second, which is off by one.
How to talk through it
- 1Clarify. Is the list sorted? Can two hits share a second? Can the duration be 0?
- 2Give the brute force. Mark every poisoned second in a set; say why attacks × duration is too much.
- 3Spot the reset. A hit only owns the seconds before the next hit, at most the duration.
- 4Code the one pass. Add min(gap, duration) for each neighbour pair, then the last duration.
- 5Test out loud. Run the equal-times and duration-0 cases, and a gap equal to the duration.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?