Asteroid Collision

Pattern: Monotonic stack

medium

Keep a stack of survivors. A left-moving asteroid fights right-movers on top of the stack: it destroys smaller ones and keeps going, dies with an equal one, or dies against a larger one. If it survives, push it.

The problem

Each value is an asteroid: its size is the absolute value and its sign is its direction (positive moves right). When two meet, the smaller explodes; equal sizes both explode. Asteroids moving the same way never meet. Return the survivors in order. [5, 10, -5] gives [5, 10]; [8, -8] gives [].

Think first

  • Which pairs can meet?
  • Which survivors can a new left-mover hit?
  • When does it stop fighting?

Hints

    Brute force, and why it fails

    Simulate collisions by scanning the list repeatedly until nothing changes: O(n²).

    The key insight

    Only the most recent survivors can be hit, in order from the latest, so the survivor list is a stack and each asteroid is pushed and popped once.

    Dry run

    100 
    21 
    -52 
    stack10 2

    asteroids = [10, 2, -5]. Push 10, push 2.

    Step 1 of 3

    The plan

    for a in asteroids:
        alive = true
        while alive and a < 0 and stack and top > 0:
            if top < -a: pop
            elif top == -a: pop; alive = false
            else: alive = false
        if alive: push a
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    Each asteroid is pushed and popped at most once.

    Edge cases

    • Left-movers first, such as [-2, -1, 1, 2]: nothing meets.
    • Equal sizes: both go.
    • One left-mover destroys many right-movers.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int[] asteroidCollision(int[] asteroids) {
            Deque<Integer> st = new ArrayDeque<>();         // survivors so far, the last one on top
            for (int a : asteroids) {
                boolean alive = true;
                while (alive && a < 0 && !st.isEmpty() && st.peek() > 0) {   // a moves left into a right-mover
                    int b = st.peek();
                    if (b < -a) st.pop();                   // b explodes, a keeps going
                    else if (b == -a) { st.pop(); alive = false; }   // both explode
                    else alive = false;                     // a explodes
                }
                if (alive) st.push(a);
            }
            int[] out = new int[st.size()];
            for (int i = out.length - 1; i >= 0; i--) out[i] = st.pop();
            return out;
        }
    }

    C++

    class Solution {
    public:
        vector<int> asteroidCollision(vector<int>& asteroids) {
            vector<int> st;                                 // survivors so far, the last one on top
            for (int a : asteroids) {
                bool alive = true;
                while (alive && a < 0 && !st.empty() && st.back() > 0) {   // a moves left into a right-mover
                    int b = st.back();
                    if (b < -a) st.pop_back();              // b explodes, a keeps going
                    else if (b == -a) { st.pop_back(); alive = false; }   // both explode
                    else alive = false;                     // a explodes
                }
                if (alive) st.push_back(a);
            }
            return st;
        }
    };

    Python

    class Solution:
        def asteroidCollision(self, asteroids: list[int]) -> list[int]:
            st = []                                 # survivors so far, the last one on top
            for a in asteroids:
                alive = True
                while alive and a < 0 and st and st[-1] > 0:   # a moves left into a right-mover
                    if st[-1] < -a:
                        st.pop()                    # the right-mover explodes, a keeps going
                    elif st[-1] == -a:
                        st.pop()                    # both explode
                        alive = False
                    else:
                        alive = False               # a explodes
                if alive:
                    st.append(a)
            return st

    Common mistakes

    • Letting a right-mover collide with a left-mover that is before it.
    • Pushing the asteroid even after it exploded.

    Similar problems