while(!stack.isEmpty() && asteroid<0 && stack.peek()>0){ if(stack.peek()>Math.abs(asteroid) { break; } else if(Math.abs(asteroid)>stack.peek()) { stack.pop(); }else{ stack.pop(); break; } } if(stack.isEmpty() || asteroid>0 || stack.peek()>0) stack.push(asteroid) ======================================================== class Solution { public int[] asteroidCollision(int[] asteroids) { Stack stack=new Stack<>(); boolean found=false; for(int i=0;i0){ if(stack.peek()>Math.abs(x)){ break; }else if(stack.peek()0 || stack.peek()<0){ stack.push(x); } } } int c=0; int ans[]=new int[stack.size()]; for(Integer i:stack){ ans[c]=i; c++; } return ans; } } ===============================================================