Asteroid Collision

Medium

Topics
ArrayStackSimulation

Given nums of asteroids (absolute value = size, sign = direction: positive right, negative left), return the state after all collisions. Two moving toward each other: the smaller explodes; equal sizes both explode. Same direction never collide.

Example 1

50101-52
survivesdestroyed
Sign is direction, magnitude is size. A collision only happens when a right-mover is immediately followed by a left-mover, which is exactly the condition a stack detects: push right-movers, and pop them while an incoming left-mover is bigger. 2 of 3 survive.
Cells are the array values; the small numbers underneath are indices.
Input:  asteroids = [5,10,-5]
Output: [5,10]

Example 2

80-81
destroyed
Input:  asteroids = [8,-8]
Output: []

Example 3

10021-52
survivesdestroyed
Input:  asteroids = [10,2,-5]
Output: [10]

Constraints

  • 2 <= nums.length <= 10^4
  • -1000 <= nums[i] <= 1000
  • nums[i] != 0
Editorial — intuition, approach, complexity and pitfalls

Intuition

Asteroids move right (positive) or left (negative). A collision happens only when a right-mover is immediately followed by a left-mover — two moving the same way never meet, and a left-mover followed by a right-mover diverge.

That "immediately followed by, after earlier collisions have resolved" is a stack. Push each asteroid; before pushing a left-mover, resolve it against whatever right-movers are on top. The resolution can cascade: a big left-mover may destroy several right-movers in turn, and the stack handles that in the while loop.

Three outcomes per comparison, and getting all three right is the problem: the top is smaller (it dies, keep comparing), equal (both die, the incoming one stops), or larger (the incoming one dies).

Approach

  1. For each asteroid, assume it survives.
  2. While it is a left-mover and the stack top is a right-mover: destroy the smaller, or both if equal, updating survival.
  3. Push it if it survived.

Dry Run

asteroids = [5,10,-5]

5     stack empty            push        [5]
10    right-mover, no clash  push        [5,10]
-5    left-mover vs top 10
      |−5| = 5 < 10 -> the incoming one dies
                                          [5,10]

answer [5,10]

asteroids = [8,-8]
8   push                                  [8]
-8  |−8| == 8 -> both destroyed, incoming stops   []
answer []

asteroids = [10,2,-5]
10, 2 pushed                              [10,2]
-5 vs 2:  5 > 2  -> pop 2, keep comparing  [10]
-5 vs 10: 5 < 10 -> incoming dies          [10]
answer [10]

Complexity

  • Time — O(n): each asteroid is pushed at most once and popped at most once, so the inner while is amortised constant despite looking nested.
  • Space — O(n): the stack, which holds everything when no collisions occur.

Common Pitfalls

  • Mishandling the equal case. Both asteroids are destroyed, so pop and mark the incoming one dead — doing only one of the two is the most common bug.
  • Comparing signed values rather than magnitudes. The left-mover's size is -a.
  • Checking only that the stack is non-empty, without requiring the top to be a right-mover. Two left-movers never collide.
  • Pushing the incoming asteroid before resolving collisions.
  • Continuing to compare after the incoming asteroid has died, which can destroy survivors.

Full Solution — all languages

class Solution:
    def asteroidCollision(self, nums):
        stack = []
        for a in nums:
            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
SensAI
Beta
Tap the mic to stop voice mode