FastPrepAsteroid Collision
Problems/Asteroid Collision

Asteroid Collision

Siemens logoSiemens● MediumINTERNPHONE SCREEN
QuestionFunctionExamplesConstraints

Problem statement

Source note: The interviewer let the candidate pick any problem, and the candidate chose this classic one. The candidate solved it with a stack and then traced it by hand while the interviewer changed the input values.

The report does not give limits or example inputs. Here, the row has 2 to 10^4 nonzero values between -1000 and 1000, and you return the survivors in their original order.

The judged task matches the report at about 95%.

You are given an integer array asteroids. Each value is one asteroid, and the array lists them in a row from left to right.

The absolute value of a number is the asteroid's size. The sign is its direction: a positive value moves right and a negative value moves left. All asteroids move at the same speed.

Two asteroids collide only when the one on the left moves right and the one on the right moves left. When they collide, the smaller one explodes. If they have the same size, both explode. The surviving asteroid keeps moving and can collide again. Asteroids that move in the same direction, or away from each other, never meet.

Return the asteroids that are left after all collisions, in their original left-to-right order.

Function

asteroidCollision(asteroids: int[]) → int[]

Examples

Example 1

asteroids = [4,7,-3]return = [4,7]

The -3 moves left and meets 7, which moves right. 7 is larger, so -3 explodes.

The 4 and the 7 both move right, so they never meet. The answer is [4,7].

Example 2

asteroids = [6,-6]return = []

The 6 moves right and the -6 moves left, so they meet. They have the same size, so both explode and nothing is left.

Example 3

asteroids = [-2,-1,3,1,-4,2]return = [-2,-1,-4,2]

The -2 and -1 both move left, and nothing to their left moves right, so they never collide.

The -4 first meets 1 and destroys it, then meets 3 and destroys it. After that, the next asteroid on its left is -1, which moves the same way, so -4 survives.

The last 2 moves right, away from everything. The answer is [-2,-1,-4,2].

Constraints

  • 2 <= asteroids.length <= 10^4
  • -1000 <= asteroids[i] <= 1000
  • asteroids[i] != 0

More Siemens problems

  • Longest Palindromic SubstringPHONE SCREEN · Seen Nov 2026
  • Padded Vector Batch PipelinePHONE SCREEN · Seen Sep 2026
See Siemens hiring insights
Saved
class Solution {
    public int[] asteroidCollision(int[] asteroids) {
        // Write your solution here.
    }
}
Checking account…