InterviewPrepKit

Home / Coding / Stack

Asteroid Collision

medium Original β†—
Solving tips
  • Recognize the stack pattern: items interact only with the most recent survivors, so process left to right keeping survivors on a stack.
  • Key insight: only an incoming negative asteroid can collide, and only with positive stack tops; push positives freely.
  • For each negative, run a while loop against positive tops: pop smaller tops, die against a bigger top, and on a tie pop the top AND kill the incoming one.
  • Target O(n) time and O(n) space (each asteroid pushed/popped at most once); compare sizes as stack[-1] vs -a, and remember one incoming asteroid can destroy several survivors.

Problem

You are given a row of asteroids as an integer array. Each value’s absolute size is the asteroid’s size, and its sign is its direction: positive moves right, negative moves left. All asteroids move at the same speed.

Two asteroids collide only when a right-mover is ahead of (to the left of) a left-mover β€” they drift toward each other. On collision the smaller one explodes; if they are the same size, both explode. Asteroids moving in the same direction never meet. Resolve all collisions and return the surviving asteroids, in order.

Examples

  • [5, 10, -5] β†’ [5, 10] β€” 10 and -5 collide, -5 explodes; -5 never reaches 5.
  • [8, -8] β†’ [] β€” equal sizes, both explode.
  • [10, 2, -5] β†’ [10] β€” -5 destroys 2, then loses to 10.
  • [-2, -1, 1, 2] β†’ [-2, -1, 1, 2] β€” left-movers on the left and right-movers on the right drift apart; no collision ever happens.

Constraints

  • 2 <= asteroids.length <= 10^4
  • -1000 <= asteroids[i] <= 1000, and asteroids[i] != 0

With n up to 10^4, a re-scan-after-every-collision simulation (O(n^2)) is the naive bar; the expected solution is a single O(n) pass.

Think about it first

Hint 1 Which pairs can actually collide? Only a `+` that is somewhere to the left of a `-`. A `-` at the far left or a `+` at the far right is safe forever.
Hint 2 Process asteroids left to right and keep the survivors so far. A new right-mover can never collide with anything already placed. A new left-mover only threatens the *most recent* surviving right-movers β€” most-recent-first is a stack.
Hint 3 Push each asteroid, but before pushing a negative one, let it fight the stack top while the top is positive: pop smaller tops, die against a bigger top, and annihilate (pop and die) on a tie. Push only if it survives every fight.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.