#735

Asteroid Collision

Medium Stack simulation

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Asteroids move along a line: positive values go right, negative go left, absolute value is size. When two collide, the smaller explodes; equal sizes both explode. Return the survivors.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: right-moving and left-moving asteroids crash; what's left?

Why this works: only a left-mover arriving after a right-mover collides. The stack holds survivors; the new left-mover fights the top.

Example: [5, 10, -5]

5, 10 on stack-5 meets 10 → -5 explodes → [5, 10]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Making a left-mover collide with a left-mover or a right-mover that comes after it.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(n).
Topic: Stack & Queue
🎬 Episodes 46–52: video coming soon