Asteroid Collision — Stack Simulation

Sanjeev SharmaSanjeev Sharma
1 min read

Advertisement

Problem 280 · Asteroid Collision

Difficulty: Medium · Pattern: Stack Collision Simulation

Positive = right, negative = left. Collisions happen when a left-moving asteroid meets a right-moving one.

Solutions

# Python
def asteroidCollision(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
// 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 { alive = stack.peek() == -a ? (stack.pop()!=stack.peek()) : false; if (stack.isEmpty()) break; }
            // Simplified:
        }
        if (alive) stack.push(a);
    }
    return stack.stream().mapToInt(i->i).toArray();
}
# Python (cleaner)
def asteroidCollision(asteroids):
    stack = []
    for a in asteroids:
        while stack and a < 0 < stack[-1]:
            if stack[-1] < -a: stack.pop(); continue
            elif stack[-1] == -a: stack.pop()
            break
        else:
            stack.append(a)
    return stack

Complexity

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

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro