↓Skip to main content
  1. LeetCode/

LeetCode 495: Teemo Attacking

·2 mins· ·
LeetCode Easy Array Simulation
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-24

  • Submissions: Runtime Error → Wrong Answer ×2 → Accepted ×3

Approach
#

Each new attack resets the poison. Attack i effectively lasts min(t[i + 1] - t[i], duration): a gap longer than the duration gives the full duration, a shorter one only lasts until the next attack. The last attack is never cut short and adds the full duration (Array Template 5).

My Attempts
#

Attempt 1 read i + 1 while looping over range(len(timeSeries)), overrunning the end. Attempt 2 swapped the branches, adding the gap when it exceeded the duration instead of the duration: [2, 7], duration = 0 returned 5 instead of 0. Subtracting the overlaps passed.

Solution
#

class Solution:
    def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:
        total = duration
        for i in range(len(timeSeries) - 1):
            total += min(timeSeries[i + 1] - timeSeries[i], duration)
        return total

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • Take the smaller of the gap and the duration; with a large gap the effect is the duration, not the gap.
  • Add the last attack’s duration separately.

Interview Explanation
#

Each attack is cut short by the next, so it contributes the smaller of the gap and the duration, and the last attack adds the full duration. Time O(n).

Related

LeetCode 414: Third Maximum Number
·1 min
LeetCode Easy Array Sorting
LeetCode 414 note: track the three largest distinct values, skipping repeats, and return the maximum if fewer than three distinct values exist
LeetCode 415: Add Strings
·2 mins
LeetCode Easy Math String Simulation
LeetCode 415 note: add digit by digit from the ends with two pointers, tracking the carry, and append any leftover carry after the loop
LeetCode 448: Find All Numbers Disappeared in an Array
·1 min
LeetCode Easy Array Hash-Table
LeetCode 448 note: use the array itself as the hash table, marking nums[x - 1] negative for each x; positions still positive are the missing numbers
LeetCode 455: Assign Cookies
·2 mins
LeetCode Easy Array Two-Pointers Greedy Sorting
LeetCode 455 note: sort children and cookies, satisfying the least greedy child with the smallest cookie that suffices; each pointer walks once
LeetCode 463: Island Perimeter
·2 mins
LeetCode Easy Array Depth-First-Search Breadth-First-Search Matrix
LeetCode 463 note: each land cell contributes 4 edges, minus 2 for each land neighbor above or to the left
LeetCode 268: Missing Number
·1 min
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 note: the sum of 0..n minus the array’s sum is the missing number, which may be 0