AlgoInsight

DSA problem

Asteroid Collision

MediumStacksPattern: Stackstop600AmazonGoogleMicrosoftMetaAdobe

We are given an array asteroids of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.

Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.

The crucial observation is that a collision can only occur when a right-moving asteroid (positive) is followed somewhere later by a left-moving one (negative). So we walk left to right and simulate collisions against the most recently surviving right-mover, which is naturally the top of a stack.

The optimal approach is to scan the array and maintain a stack of surviving asteroids. For each incoming asteroid, repeatedly resolve collisions against the stack top: while the top is a positive (right-moving) asteroid and the incoming is negative (left-moving), they collide. The smaller one explodes; if they are equal both explode. After all collisions are resolved (or never started, because the top was negative or the incoming was positive), push the survivor if it still exists. This runs in O(n) total time because each asteroid is pushed at most once and popped at most once.

Examples

Example 1
Input: asteroids = [5,10,-5]
Output: [5,10]
Explanation: -5 collides with 10. The 10 is larger, so -5 explodes. 5 and 10 never meet (both right-moving). Result: [5,10].
Example 2
Input: asteroids = [8,-8]
Output: []
Explanation: 8 and -8 are equal in size and moving toward each other, so both explode.
Example 3
Input: asteroids = [10,2,-5]
Output: [10]
Explanation: -5 collides with 2 and 2 explodes (2 < 5). Then -5 collides with 10 and -5 explodes (5 < 10). Result: [10].

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

stackarraysimulation

Browse all DSA problems