A row of asteroids is given as the array asteroids. The size of each one is its absolute value, and its sign is its direction: positive moves right, negative moves left. They all fly at the same speed, and their order in the array is their order in space.
When two asteroids meet, the smaller one is destroyed; if they are the same size, both are. Two asteroids heading the same way never meet. Return the asteroids that are left once no more collisions can happen, in their original order.
Example 1
Input: asteroids = [4, 9, -6] Output: [4, 9] Why: -6 hits 9 and loses; 4 and 9 fly the same way
2 more examples and the constraints
Example 2
Input: asteroids = [7, -7] Output: [] Why: same size, so both are destroyed
Example 3
Input: asteroids = [-2, 3, 1, -5, 6] Output: [-2, -5, 6] Why: -5 destroys 1 and 3; -2 is already flying away
Constraints
- 2 ≤ length of asteroids ≤ 10,000
- −1,000 ≤ each asteroids[i] ≤ 1,000
- No asteroid is 0
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Repeat until stableO(n²)
- Stack of survivorsO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Work for 10,000 asteroids | Verdict |
|---|---|---|---|
| Repeat until stable | O(n²) | Correct, but rescans | |
| Stack of survivors | O(n) | Best; one pass |
n = number of asteroids.
Edge cases to test
- Left-movers before right-movers. [-3, -1, 2, 5]: the two groups fly apart, so nothing collides.
- Equal sizes. [7, -7] leaves an empty row; both are destroyed.
- One left-mover clears the row. [1, 2, 3, -10] pops three times and leaves [-10].
- A big right-mover holds. [10, -1, -2, -3]: each left-mover dies on 10 and nothing is popped.
Common mistakes
- Letting a right-mover on the stack collide with a new right-mover, or a left-mover on the stack with a new right-mover. Only top > 0 and x < 0 meet.
- Stopping after the first pop, when the left-mover may still destroy more asteroids beneath it.
- Forgetting the tie case, so equal sizes leave one survivor instead of none.
How to talk through it
- 1Clarify. Do equal sizes destroy both? Should the answer keep the original order? Can sizes be zero?
- 2Say when two meet. Only a right-mover with a left-mover directly after it. Everything else flies apart or in parallel.
- 3Give the slow version. Resolve one colliding pair per scan until nothing changes; say it is O(n²).
- 4Use a stack. The survivors so far are stable. A new left-mover only fights the top, so a stack handles it in O(n) overall.
- 5Test out loud. Run [7, -7], [1, 2, 3, -10] and [-3, -1, 2, 5] to cover ties, chain pops and no collisions.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?