AceYourInterviews
Checking sign-in…

47. Asteroid Collision

IntermediateStable survivor stack with cascading directional collisions

Asteroids move at equal speed, with the sign describing direction and the magnitude describing size. Resolve collisions between asteroids moving toward one another until no further collision can occur.

A larger asteroid survives a collision; equal-sized opposing asteroids both disappear. Surviving asteroids can collide again, so one collision can trigger a chain reaction.

Example 1

Input

[10,2,-5]

Output

[10]

Explanation: The incoming -5 destroys 2, then is destroyed by 10; one collision is not enough.

Example 2

Input

[-2,-1,1,2]

Output

[-2,-1,1,2]

Explanation: Same-direction neighbors and outward-moving opposite signs never approach.

Constraints

  • 0 <= asteroids.length <= 105
  • -231 <= asteroids[i] <= 231 - 1
  • asteroids[i] != 0.
Hints
Hint 1

Which processed survivor would a new asteroid encounter first?

Hint 2

Can destroying one survivor expose another collision?

Hint 3

Loop only for positive-top/negative-incoming pairs and preserve the incoming liveness state.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

A cascade exposes a larger survivor

[10,2,-5]
[10]