InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Stack

Asteroid Collision

medium Original ↗ 00:00

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 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug