Skip to content

Commit d988b52

Browse files
authored
Feature/735 asteroid collision (#30)
* feat: [LeetCode #735] Asteroid Collision Тип: Сложность: Временная сложность: O() Пространственная сложность: O() Краткое описание решения: - Ссылка: https://leetcode.com/problems/asteroid-collision/ * feat: [LeetCode #735] Asteroid Collision Тип: Stack Сложность: medium Временная сложность: O(n) Пространственная сложность: O(1) - Ссылка: https://leetcode.com/problems/asteroid-collision/
1 parent a22aa65 commit d988b52

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

src/stack/asteroid_collision/__init__.py

Whitespace-only changes.
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution:
2+
def asteroidCollision(self, asteroids: list[int]) -> list[int]:
3+
stack = []
4+
for asteroid in asteroids:
5+
while asteroid:
6+
try:
7+
left_asteroid = stack.pop()
8+
if asteroid > 0 or (asteroid < 0 and left_asteroid < 0):
9+
stack.extend([left_asteroid, asteroid])
10+
asteroid = None
11+
else:
12+
if abs(asteroid) == abs(left_asteroid):
13+
asteroid = None
14+
elif abs(asteroid) < abs(left_asteroid):
15+
stack.append(left_asteroid)
16+
asteroid = None
17+
except IndexError:
18+
stack.append(asteroid)
19+
asteroid = None
20+
return stack

tests/test_asteroid_collision.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import pytest
2+
from src.stack.asteroid_collision.solution import (
3+
Solution,
4+
)
5+
6+
7+
@pytest.mark.parametrize(
8+
"asteroids, expected",
9+
[
10+
([5, 10, -5], [5, 10]),
11+
([8, -8], []),
12+
([10, 2, -5], [10]),
13+
([3, 5, -6, 2, -1, 4], [-6, 2, 4]),
14+
],
15+
)
16+
def test_asteroid_collision(asteroids, expected):
17+
solution = Solution()
18+
assert solution.asteroidCollision(asteroids) == expected

0 commit comments

Comments
 (0)