Asteroid Collision

Stack — push each asteroid; on a right-moving stack top vs left-moving incoming, pop the smaller (or both if equal).

Medium
Time O(n) Space O(n)
LeetCode
3 min read
stack array simulation

Problem#

Positive integers move right, negatives move left, all at the same speed. On collision, the smaller (by absolute value) explodes; equal sizes destroy each other. Return the surviving asteroids.

Examples#

  • [5,10,-5][5,10].
  • [8,-8][]; [10,2,-5][10].

Constraints#

  • 2 <= asteroids.length <= 10^4.

Approach#

Stack of survivors. For each new asteroid, while it’s negative and the stack top is positive: if |top| < |new|, pop and continue; if equal, pop and discard the new one; if |top| > |new|, discard the new one. Else push.

Solution#

Asteroid Collision
class Solution {
public:
vector<int> asteroidCollision(vector<int>& a) {
vector<int> st;
for (int x : a) {
bool alive = true;
while (alive && x < 0 && !st.empty() && st.back() > 0) {
if (st.back() < -x) st.pop_back();
else if (st.back() == -x) { st.pop_back(); alive = false; }
else alive = false;
}
if (alive) st.push_back(x);
}
return st;
}
};

Editorial#

The only collision occurs when a leftward asteroid meets a rightward survivor on the stack. The stack invariant — “right-movers followed by left-movers” — means once a left-mover is appended, it never collides again. Each asteroid is pushed at most once and popped at most once.

Complexity#

  • Time: O(n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.