Skip to content

Commit 5aeadc1

Browse files
committed
solve Teemo Attacking
1 parent 9f513c9 commit 5aeadc1

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

problems/teemo_attacking.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
# timeSeries = [1, 3, 8, 19], duration = 5
6+
def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:
7+
ans, last = 0, float("-inf")
8+
for t in timeSeries:
9+
ans += duration
10+
if (t - last) < duration:
11+
ans -= duration - (t - last)
12+
last = t
13+
return ans
14+
15+
16+
class OfficialSolution:
17+
def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:
18+
"""
19+
The problem is an example of merge interval questions which are now quite
20+
popular in Google.
21+
Typically such problems could be solved in linear time in the case of sorted
22+
input, and in O(nlgn) time otherwise.
23+
Here one deals with a sorted input, and the problem could be solved in one pass
24+
with a constant space. The idea is straightforward: consider only the interval
25+
between two attacks. Ashe spends in a poisoned condition the whole time interval
26+
if this interval is shorter than the poisoning time duration, and duration
27+
otherwise.
28+
29+
== Algorithm ==
30+
- Initiate total time in poisoned condition, total = 0.
31+
- Iterate over timeSeries list. At each step add to the total time the minimum
32+
between interval length and the poisoning time duration.
33+
- Return total + duration to take the last attack into account.
34+
35+
== Complexity Analysis ==
36+
- Time Complexity: O(n) where n is the length of the input list, since we
37+
iterate the entire list.
38+
- Space Complexity: O(1), it's a constant space solution.
39+
"""
40+
n = len(timeSeries)
41+
if n == 0:
42+
return 0
43+
44+
total = 0
45+
for i in range(n - 1):
46+
total += min(timeSeries[i + 1] - timeSeries[i], duration)
47+
return total + duration

tests/test_teemo_attacking.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import unittest
2+
3+
from teemo_attacking import Solution, OfficialSolution
4+
5+
6+
class TestTeemoAttacking(unittest.TestCase):
7+
def test_example_1(self):
8+
assert Solution().findPoisonedDuration(timeSeries=[1, 4], duration=2) == 4
9+
assert (
10+
OfficialSolution().findPoisonedDuration(timeSeries=[1, 4], duration=2) == 4
11+
)
12+
13+
def test_example_2(self):
14+
assert Solution().findPoisonedDuration(timeSeries=[1, 2], duration=2) == 3
15+
assert (
16+
OfficialSolution().findPoisonedDuration(timeSeries=[1, 2], duration=2) == 3
17+
)

0 commit comments

Comments
 (0)