Teemo Attacking - Problem

Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for 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.

Input & Output

Example 1 — Basic Case
$ Input: timeSeries = [1,4], duration = 2
Output: 4
💡 Note: Attack at t=1: poison from [1,2]. Attack at t=4: poison from [4,5]. Total: 2 + 2 = 4 seconds
Example 2 — Overlapping Attacks
$ Input: timeSeries = [1,2], duration = 2
Output: 3
💡 Note: Attack at t=1: poison [1,2]. Attack at t=2 resets timer: poison [2,3]. Total unique seconds: 1,2,3 = 3 seconds
Example 3 — Single Attack
$ Input: timeSeries = [1], duration = 3
Output: 3
💡 Note: Only one attack at t=1, poison lasts for 3 seconds: [1,2,3]

Constraints

  • 1 ≤ timeSeries.length ≤ 104
  • 0 ≤ timeSeries[i], duration ≤ 107
  • timeSeries is sorted in non-decreasing order

Visualization

Tap to expand
Teemo Attacking - Gap Analysis Approach INPUT timeSeries Array 1 index 0 4 index 1 duration = 2 2 seconds Timeline View 0 1 2 3 4 5 Attack 1 Attack 2 [1,2] [4,5] Poison intervals shown ALGORITHM STEPS 1 Initialize total = 0 Start with zero poisoned seconds 2 Loop through attacks For i = 0 to n-2 3 Calculate gap gap = time[i+1] - time[i] Add min(gap, duration) 4 Add last attack total += duration Example Calculation: gap = 4 - 1 = 3 min(3, 2) = 2 (no overlap) total = 2 + 2 = 4 FINAL RESULT Total Poisoned Seconds 4 Breakdown: Attack at t=1: +2 sec Attack at t=4: +2 sec Total: 4 sec OK - Verified No overlapping intervals Key Insight: Gap Analysis For each consecutive pair of attacks, compare the gap between them with the poison duration. If gap >= duration: full poison time (no overlap). If gap < duration: poison resets (add only gap). Time Complexity: O(n) | Space Complexity: O(1) - Single pass through the array! TutorialsPoint - Teemo Attacking | Gap Analysis Approach
Asked in
Google 15 Amazon 12 Microsoft 8
28.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen