sagelearnai

Asteroid Collision

Difficulty: Medium · Pattern: Stack & Monotonic Stack · LeetCode #735

Each asteroid's absolute value is its size and its sign its direction (positive = right, negative = left); all move at the same speed. When two meet, the smaller explodes (if they're equal, both do). Asteroids moving in the same direction never meet. Return the state after all collisions.

Examples

text
[5, 10, -5]   →  [5, 10]
[8, -8]       →  []
[10, 2, -5]   →  [10]
[-2, -1, 1, 2] →  [-2, -1, 1, 2]

Hints

  1. Collisions only happen when a right-mover is followed by a left-mover.
  2. Keep survivors on a stack; a new left-mover collides with right-movers on top.

Approach

Iterate asteroids. For a negative asteroid a, while the stack top is positive and smaller than |a|, pop it (it explodes). Then: if the top is positive and equal in size, pop it, and a dies too; if the top is positive and larger, a dies; otherwise push a. Positive asteroids are always pushed. Each asteroid is pushed and popped at most once, so O(n).

Complexity

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

Python solution
def asteroidCollision(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
JavaScript solution
function asteroidCollision(asteroids) {
  const st = [];
  for (const a of asteroids) {
    let alive = true;
    while (alive && a < 0 && st.length && st[st.length - 1] > 0) {
      const top = st[st.length - 1];
      if (top < -a) st.pop();
      else { if (top === -a) st.pop(); alive = false; }
    }
    if (alive) st.push(a);
  }
  return st;
}