Asteroid Collision

Medium StackArraySimulation

Problem

Each value in asteroids is the absolute size and direction (positive = right, negative = left). Same direction never collide. Opposite-direction collisions destroy the smaller; equal destroys both. Return the survivors.

Example 1 Input: [5,10,-5] Output: [5, 10]
Example 2 Input: [8,-8] Output: []
Example 3 Input: [10,2,-5] Output: [10]

Constraints

Approach — Stack

This is a Stack problem. The idea: scan the input once, pushing work onto a stack and popping when the top can be resolved, so the stack always reflects what's still open. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(n) time, O(n) space.

Solution code

Python

class Solution:
    def asteroidCollision(self, asteroids):
        st = []
        for a in asteroids:
            alive = True
            while alive and a < 0 and st and st[-1] > 0:
                if st[-1] < -a:
                    st.pop()
                elif st[-1] == -a:
                    st.pop(); alive = False
                else:
                    alive = False
            if alive:
                st.append(a)
        return st

Java

import java.util.Stack;

class Solution {
    public int[] asteroidCollision(int[] asteroids) {
        Stack<Integer> stack = new Stack<>();
        for (int ast: asteroids) {
            collision: {
                while (!stack.empty() && ast < 0 && 0 < stack.peek()) {
                    if (stack.peek() < -ast) {
                        stack.pop();
                        continue;
                    } else if (stack.peek() == -ast) {
                        stack.pop();
                    }
                    break collision;
                }
                stack.push(ast);
            }
        }

        int[] ans = new int[stack.size()];
        for (int t = ans.length - 1; t >= 0; --t) {
            ans[t] = stack.pop();
        }
        return ans;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Asteroid Collision interactively → ← All solutions