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

Edge cases to test

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 stack

C++

#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