Asteroid Collision Visualizer & Step-by-Step Algorithm Solution

Simulate asteroid collisions where positive asteroids move right and negative move left. Smaller asteroids explode upon impact.

Category: stack | Difficulty: Medium

Tags: Stack, Simulation, Array

Asteroid Collision

Asteroids Lane (+ Right, - Left)
5
0
10
1
-5
2
Push / Pop (Top)
(Empty Stack)
Surviving Space Stack
100%
state
stack.length0
Initialization
1/10
Explanation

Initialize empty stack to track surviving asteroids.

Source Code
1function asteroidCollision(asteroids) {
2 const stack = [];
3 for (let i = 0; i < asteroids.length; i++) {
4 const a = asteroids[i];
5 let destroyed = false;
6 while (stack.length && a < 0 && stack[stack.length - 1] > 0) {
7 const top = stack[stack.length - 1];
8 if (top > -a) {
9 destroyed = true;
10 break;
11 } else if (top === -a) {
12 destroyed = true;
13 stack.pop();
14 break;
15 } else {
16 stack.pop();
17 }
18 }
19 if (!destroyed) stack.push(a);
20 }
21 return stack;
22}