Workspace Asteroid Collision
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Asteroid Collision visualizer

Learn Asteroid Collision with a step-by-step Stacks & Queues visualizer, JavaScript source code and a worked example. Practice monotonic structures.

INTERACTIVE EXECUTION STUDIO
LEARN BY DOING

Predict. Execute. Understand.

Follow the source code, inspect live state changes, and predict the next operation before revealing it.

1 / 5Execution step
Reference example · JavaScript
Inspect reference input
[
  5,
  10,
  -5
]

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (a,s)=>{
let st=[];
for(let x of a){
let ok=true;
while(ok&&x<0&&st.at(-1)>0){
if(st.at(-1)<-x)st.pop();
else if(st.at(-1)===-x){
st.pop();
ok=false
}else ok=false;
s("Resolve opposing asteroids",{
Stack:st,Incoming:[x]
})
}
if(ok)st.push(x);
s("Keep survivors",{
Stack:st
})
}
return st
};

Execution canvas

Active Changed
STEP 1

Keep survivors

Inspect the highlighted code and the state below. Click individual cells or nodes to see their values.

Stack1 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Stacks & Queues · Monotonic structures

Follow the computed execution on the reference input. Advance one step at a time, inspect the changing values and compare your prediction with the final output.

Example input

[
  5,
  10,
  -5
]

Execution steps

  1. Keep survivors
  2. Resolve opposing asteroids

Computed output

[
  5,
  10
]
JavaScript reference implementation
const solve = (a,s)=>{
  let st=[];
  for(let x of a){
    let ok=true;
    while(ok&&x<0&&st.at(-1)>0){
      if(st.at(-1)<-x)st.pop();
      else if(st.at(-1)===-x){
        st.pop();
        ok=false
      }else ok=false;
      s("Resolve opposing asteroids",{
        Stack:st,Incoming:[x]
      })
    }
    if(ok)st.push(x);
    s("Keep survivors",{
      Stack:st
    })
  }
  return st
};

Continue learning

Practice related DSA questions in the same topic.