We are given an array asteroids of integers representing asteroids in a row. The indices of the asteriod in the array represent their relative position in space.
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
Example 1:
Input: asteroids = [5,10,-5]
Output: [5,10]
Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
Example 2:
Input: asteroids = [8,-8]
Output: []
Explanation: The 8 and -8 collide exploding each other.
Example 3:
Input: asteroids = [10,2,-5]
Output: [10]
Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
Constraints:
2 <= asteroids.length <= 104
-1000 <= asteroids[i] <= 1000
asteroids[i] != 0
class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = []
for asteroid in asteroids:
if asteroid > 0:
stack.append(asteroid)
else:
# Incoming asteroid is bigger, remove many as needed
while stack and stack[-1] > 0 and stack[-1] < abs(asteroid):
stack.pop()
# Both explode
if stack and stack[-1] > 0 and stack[-1] == abs(asteroid):
stack.pop()
# Add initial and as many negatives
elif not stack or stack[-1] < 0:
stack.append(asteroid)
return stack
🐍The Stack: Our Asteroid Holding Area
Think of stack as a place where we temporarily keep the asteroids we've seen so far, in the order we encountered them. It helps us keep track of who's going to collide with whom.
🐍Going Through Each Asteroid
The code looks at each asteroid in the asteroids list, one by one.
🐍Positive Asteroids (Moving Right)
If an asteroid is positive (moving right), it’s safe for now. We simply add it to the stack. It will only collide with something coming from the right, which we haven't seen yet.
🐍Negative Asteroids (Moving Left) — The Collisions
🐍“While Loop: Bigger Negative Eats Smaller Positives”
🐍Equal Size: Boom!
🐍Negative Survives or Nothing to Collide With
If the stack is empty (meaning no positive asteroids were left), or if the top of the stack is a negative asteroid, it means the current negative asteroid survives. We add it to the stack.
🐍The Survivors
function asteroidCollision(asteroids: number[]): number[] {
const stack: number[] = [];
for (const asteroid of asteroids) {
if (asteroid > 0) {
stack.push(asteroid);
} else {
while (stack.length > 0 && stack[stack.length - 1] > 0 && stack[stack.length - 1] < Math.abs(asteroid)) {
stack.pop();
}
if (stack.length > 0 && stack[stack.length - 1] > 0 && stack[stack.length - 1] === Math.abs(asteroid)) {
stack.pop();
} else if (stack.length === 0 || stack[stack.length - 1] < 0) {
stack.push(asteroid);
}
}
}
return stack;
}
🟡The Stack (Imagine a Line of Asteroids):
🟡Looking at Each Asteroid One by One:
🟡Left-Moving Asteroids (Negative Numbers):
🟡Checking for Collisions:
🟡Same Size Collision:
🟡No Collision or Left-Moving Survives:
🟡The Survivors:
func asteroidCollision(asteroids []int) []int {
stack := []int{}
for _, asteroid := range asteroids {
if asteroid > 0 {
stack = append(stack, asteroid)
} else {
for len(stack) > 0 && stack[len(stack)-1] > 0 && stack[len(stack)-1] < -asteroid {
stack = stack[:len(stack)-1]
}
if len(stack) > 0 && stack[len(stack)-1] > 0 && stack[len(stack)-1] == -asteroid {
stack = stack[:len(stack)-1]
} else if len(stack) == 0 || stack[len(stack)-1] < 0 {
stack = append(stack, asteroid)
}
}
}
return stack
}
🔵Going Right? Stack It!
🔵Going Left? Collision Time!
🔵Left Survives or Nothing to Collide:
🔵The Survivors:
If you liked this content I’d appreciate an upvote or a comment. That helps me improve the quality of my posts as well as getting to know more about you, my dear reader.
Muchas gracias!
Follow me for more content like this.
X | PeakD | Rumble | YouTube | Linked In | GitHub | PayPal.me | Medium
Down below you can find other ways to tip my work.
BankTransfer: "710969000019398639", // CLABE
BAT: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875",
ETH: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875",
BTC: "33xxUWU5kjcPk1Kr9ucn9tQXd2DbQ1b9tE",
ADA: "addr1q9l3y73e82hhwfr49eu0fkjw34w9s406wnln7rk9m4ky5fag8akgnwf3y4r2uzqf00rw0pvsucql0pqkzag5n450facq8vwr5e",
DOT: "1rRDzfMLPi88RixTeVc2beA5h2Q3z1K1Uk3kqqyej7nWPNf",
DOGE: "DRph8GEwGccvBWCe4wEQsWsTvQvsEH4QKH",
DAI: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875"