Asteroid Collision

MediumStackstack simulation

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an array asteroids of nonzero integers describing a row of asteroids moving along a one-dimensional line. For each asteroid, the absolute value abs(asteroids[i]) represents its size, and the sign represents its direction of travel: - A **positive** value means the asteroid is moving to the **right**. - A **negative** value means the asteroid is moving to the **left**. All asteroids move at the same constant speed. A collision happens only when a right-moving asteroid is immediately followed (to its right) by a left-moving asteroid, so they are heading toward each other. When two asteroids collide: - The **smaller** one explodes and disappears. - If both have the **same** size, **both** explode. - The **larger** one survives unchanged. Two asteroids moving in the same direction, or moving apart, will never collide. Return the state of the row after all collisions have resolved, as an array of the surviving asteroids in their original left-to-right order.

Examples

Input: asteroids = [5, 10, -5]
Output: [5, 10]
The `10` and the `-5` collide; `10` is larger so `-5` explodes. The `10` and `5` both move right, so they never collide.
Input: asteroids = [8, -8]
Output: []
The `8` (right) and `-8` (left) move toward each other and are equal in size, so both explode, leaving nothing.
Input: asteroids = [10, 2, -5]
Output: [10]
The `2` and `-5` collide, destroying `2`. The surviving `-5` then meets `10` and explodes, leaving only `10`.

Constraints

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

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.