Algo-Sim › Stacks & Monotonic Stack
Asteroid Collision
Medium · Stacks & Monotonic Stack · step through it in Java, Python and C++ on your own input
A stack of survivors: only a left-mover meeting a right-mover on top collides, and it keeps colliding until it loses or the way is clear.
Problem
Each value in asteroids is an asteroid in a row: its absolute value is its size and its sign its direction (positive moves right, negative left), all at the same speed. When two meet, the smaller explodes, and equal sizes both explode. Return the asteroids left after every collision, in order.
Constraints
- 2 ≤ asteroids.length ≤ 10⁴
- -1000 ≤ asteroids[i] ≤ 1000
- asteroids[i] ≠ 0
Edge cases to test
- Equal sizes: both explode
- Everything moving the same way: nothing collides
- A big left-mover that destroys the whole stack
Follow-up questions
- Why do only right-then-left pairs collide?
- A left-mover in front of a right-mover moves away from it, so only a right-mover on the stack facing a new left-mover can meet.
- Why is it O(n)?
- Each asteroid is pushed and popped at most once.
Solution
Java
public int[] asteroidCollision(int[] asteroids) {
Deque<Integer> stack = new ArrayDeque<>();
for (int a : asteroids) {
boolean alive = true;
while (alive && a < 0 && !stack.isEmpty() && stack.peek() > 0) {
if (stack.peek() < -a) stack.pop();
else if (stack.peek() == -a) { stack.pop(); alive = false; }
else alive = false;
}
if (alive) stack.push(a);
}
int[] out = new int[stack.size()];
for (int i = out.length - 1; i >= 0; i--) out[i] = stack.pop();
return out;
}Python
def asteroid_collision(asteroids):
stack = []
for a in asteroids:
alive = True
while alive and a < 0 and stack and stack[-1] > 0:
if stack[-1] < -a: stack.pop()
elif stack[-1] == -a: stack.pop(); alive = False
else: alive = False
if alive: stack.append(a)
return stackC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> asteroidCollision(vector<int> &asteroids) {
vector<int> stack = {};
for (int a : asteroids) {
bool alive = true;
while (alive && a < 0 && !stack.empty() && stack.back() > 0) {
if (stack.back() < -a) stack.pop_back();
else if (stack.back() == -a) stack.pop_back(), alive = false;
else alive = false;
}
if (alive) stack.push_back(a);
}
return stack;
}
};
More Stacks & Monotonic Stack problems
- Valid Parentheses (Easy)
- Implement Queue using Stacks (Easy)
- Evaluate Reverse Polish Notation (Medium)
- Basic Calculator II (Medium)
- Basic Calculator (Hard)
- Decode String (Medium)
- Next Greater Element (Easy)
- Daily Temperatures (Medium)
- Remove K Digits (Medium)
- Online Stock Span (Medium)
- Car Fleet (Medium)
- Largest Rectangle in Histogram (Hard)
- Maximal Rectangle (Hard)
- Sliding Window Maximum (Hard)