Asteroid Collision Problem | Python Stack Solution #Python #LeetCode #Coding #DSA #Stack #Algorithm

preview_player
Показать описание
💡 Asteroid Collision is a LeetCode 75 problem that requires simulating asteroid movements and resolving collisions between them based on size and direction. In this video/article, we break down an efficient stack-based approach to solve this problem in O(n) time complexity.

🔹 Problem Breakdown

We are given an array of integers where:

✔️ Each integer represents an asteroid, its absolute value denotes its size.
✔️ The sign of the integer determines the direction:

Positive (+) → Asteroid moves right → ➡️
Negative (-) → Asteroid moves left → ⬅️

✔️ If two asteroids collide, the smaller one explodes. If both are of equal size, both are destroyed.

✔️ Asteroids moving in the same direction will never collide.

🔹 Stack-Based Approach (Optimal Solution - O(n))

🔸 We iterate through the array using a stack to simulate collisions dynamically:

1️⃣ If the asteroid is positive (+), push it onto the stack.

2️⃣ If the asteroid is negative (-), check for possible collisions with the top of the stack:

If the top asteroid is also negative (-) → No collision, push onto the stack.
If the top asteroid is positive (+) → Compare their sizes:
If the left-moving asteroid is larger, it destroys the right-moving one.
If both are equal, both are destroyed.
If the right-moving asteroid is larger, it remains, and the new asteroid is ignored.

3️⃣ Continue iterating until all collisions are resolved.

🔹 Python Code Implementation

class Solution:
def asteroidCollision(self, asteroids):
stack = []

for asteroid in asteroids:
while stack and asteroid v 0 and stack[-1] v 0:
if abs(stack[-1]) v abs(asteroid):
continue
elif abs(stack[-1]) == abs(asteroid):
break
else:

return stack

# Example Test Cases

sol = Solution()

⏳ Time & Space Complexity Analysis

✅ Time Complexity: O(n) → Each asteroid is processed at most once (push/pop operations are O(1)).
✅ Space Complexity: O(n) → In the worst case (no collisions), we store all asteroids in the stack.

🔥 Why Use a Stack?

✔️ Stack helps track asteroids dynamically.
✔️ Efficient pop operations allow handling collisions optimally.
✔️ Iterates only once, making it O(n) time complexity.

📌 Example Walkthrough

Example 1: asteroids = [5,10,-5]

Step 1: 5 → Push onto stack → [5]
Step 2: 10 → Push onto stack → [5,10]
Step 3: -5 → Collision with 10 → 10 survives → [5,10]

✅ Final Output: [5,10]

Example 2: asteroids = [8,-8]

Step 1: 8 → Push onto stack → [8]
Step 2: -8 → Equal size collision → Both explode → []

✅ Final Output: []

🎯 Key Takeaways

🔹 Stack efficiently handles dynamic asteroid collisions.
🔹 O(n) optimal solution using a single pass iteration.
🔹 Each asteroid is processed at most once (push/pop operations).

📌 Like, Share & Save for Future Reference! 🚀

#LeetCode #Python #Stack #Algorithm #DataStructures #AsteroidCollision #DSA #CompetitiveProgramming
Рекомендации по теме
join shbcf.ru